【JavaFx教程】第六部分:統計圖

Screenshot AddressApp Part 6

第6部分的主題

  • 創建一個統計圖顯示生日的分佈。

生日統計

在AddressApp中所有人員都有生日。當我們人員慶祝他們生日的時候,如果有一些生日的統計不是會更好。

我們使用柱狀圖,包含每個月的一個條形。每個條形顯示在指定月份中有多少人需要過生日。

統計FXML視圖

  1. ch.makery.address.view包中我們開始創建一個BirthdayStatistics.fxml(*右擊包|New|other..|New FXML Document*) 生日統計FXML

  2. 在Scene Builder中打開BirthdayStatistics.fxml文件。

  3. 選擇根節點AnchorPane。在*Layout*組中設置*Pref Width*爲620,*Pref Height*爲450。

  4. 添加BarChartAnchorPane中。

  5. 右擊BarChart並且選擇*Fit to Parent*。

  6. 保存fxml文件,進入到Eclipse中,F5刷新項目。

在我們返回到Scene Builder之前,我們首先創建控制器,並且在我們的MainApp中準備好一切。

統計控制器

在view包 ch.makery.address.view中創建一個Java類,稱爲BirthdayStatisticsController.java

在開始解釋之前,讓我們看下整個控制器類。

BirthdayStatisticsController.java

package ch.makery.address.view;

import java.text.DateFormatSymbols;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.XYChart;
import ch.makery.address.model.Person;

/**
 * The controller for the birthday statistics view.
 * 
 * @author Marco Jakob
 */
public class BirthdayStatisticsController {

    @FXML
    private BarChart<String, Integer> barChart;

    @FXML
    private CategoryAxis xAxis;

    private ObservableList<String> monthNames = FXCollections.observableArrayList();

    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     */
    @FXML
    private void initialize() {
        // Get an array with the English month names.
        String[] months = DateFormatSymbols.getInstance(Locale.ENGLISH).getMonths();
        // Convert it to a list and add it to our ObservableList of months.
        monthNames.addAll(Arrays.asList(months));
        
        // Assign the month names as categories for the horizontal axis.
        xAxis.setCategories(monthNames);
    }

    /**
     * Sets the persons to show the statistics for.
     * 
     * @param persons
     */
    public void setPersonData(List<Person> persons) {
        // Count the number of people having their birthday in a specific month.
        int[] monthCounter = new int[12];
        for (Person p : persons) {
            int month = p.getBirthday().getMonthValue() - 1;
            monthCounter[month]++;
        }

        XYChart.Series<String, Integer> series = new XYChart.Series<>();
        
        // Create a XYChart.Data object for each month. Add it to the series.
        for (int i = 0; i < monthCounter.length; i++) {
            series.getData().add(new XYChart.Data<>(monthNames.get(i), monthCounter[i]));
        }
        
        barChart.getData().add(series);
    }
}

控制器如何工作

  1. 控制器需要從FXML文件中訪問兩個元素:

    • barChar:它有StringInteger類型。String用於x軸上的月份,Integer用於指定月份中人員的數量。
    • xAxis:我們使用它添加月字符串
  2. initialize() 方法使用所有月的列表填充x-axis

  3. setPersonData(…)方法將由MainApp訪問,設置人員數據。它遍歷所有人員,統計出每個月生日的人數。然後它爲每個月添加XYChart.Data到數據序列中。每個XYChart.Data對象在圖表中表示一個條形。


連接視圖和控制器

  1. 在Scene Builder中打開BirthdayStatistics.fxml

  2. Controller組中設置BirthdayStatisticsController爲控制器。

  3. 選擇BarChart,並且選擇barChar作爲fx:id屬性(在*Code*組中)

  4. 選擇CategoryAxis,並且選擇xAxis作爲fx:id屬性。
    類別軸

  5. 你可以添加一個標題給BarChar(在*Properties*組中)進一步修飾。


連接View/Controller和MainApp

我們爲*生日統計*使用與*編輯人員對話框*相同的機制,一個簡單的彈出對話框。

添加下面的方法到MainApp類中

/**
 * Opens a dialog to show birthday statistics.
 */
public void showBirthdayStatistics() {
    try {
        // Load the fxml file and create a new stage for the popup.
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("view/BirthdayStatistics.fxml"));
        AnchorPane page = (AnchorPane) loader.load();
        Stage dialogStage = new Stage();
        dialogStage.setTitle("Birthday Statistics");
        dialogStage.initModality(Modality.WINDOW_MODAL);
        dialogStage.initOwner(primaryStage);
        Scene scene = new Scene(page);
        dialogStage.setScene(scene);

        // Set the persons into the controller.
        BirthdayStatisticsController controller = loader.getController();
        controller.setPersonData(personData);

        dialogStage.show();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

一切設置完畢,但是我們沒有任何東西實際上調用新的showBirthdayStatistics()方法。幸運的是我們已經在RootLayout.fxml中有一個菜單,它可以用於這個目的。

顯示生日統計菜單

RootLayoutController中添加下面的方法,它將處理*顯示生日統計*菜單項的用戶點擊。

/**
 * Opens the birthday statistics.
 */
@FXML
private void handleShowBirthdayStatistics() {
  mainApp.showBirthdayStatistics();
}

現在,使用Scene Builder打開RootLayout.fxml文件。創建Staticstic 菜單,帶有一個Show Statistcs MenuItem:

Show Statistics菜單

選擇Show Statistics MenuItem,並且選擇handleShowBirthdayStatistics作爲On Action(在*Code*組中)。

Show Statistics On Action

進入到Eclipse,刷新項目,測試它


JavaFX Chart的更多信息

更多信息的一個好地方是官方Oracle教程,使用JavaFX Chart.

下一步做什麼?

在最後的教程第7部分 中,我們將最後部署我們的應用(例如:打包並且發佈應用到我們的用戶)

--------------------- 本文來自 jobbible 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/moshenglv/article/details/82877735?utm_source=copy 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章