如何使用 JavaFX 建立面積圖?


面積圖接收一系列資料點 (x, y) 作為輸入值,使用線條連線它們,並對映獲得的線條和軸之間的區域。在 JavaFX 中,您可以透過例項化 **javafx.scene.chart.AreaChart** 類來建立面積圖。

在例項化此類時,您必須傳遞代表 x 軸和 y 軸的兩個 Axis 類物件(作為建構函式的引數)。由於 Axis 類是抽象類,因此您需要傳遞其具體子類的物件,例如 NumberAxis(用於數值)或 CategoryAxis(用於字串值)。

建立軸後,您可以使用 **setLabel()** 方法為其設定標籤。

設定資料

**XYChart.Series** 表示資料項的系列。您可以透過例項化此類來建立線條的一系列點。此類包含一個可觀察列表,其中包含系列中的所有點。

**XYChart.Data** 表示 x-y 平面中的特定資料點。要建立點,您需要透過傳遞該點的 x 和 y 值來例項化此類。

因此,要為線條建立資料 -

  • 透過例項化 **XYChart.Data** 類建立所需數量的點。

  • 透過例項化 **XYChart.Series** 類建立系列。

  • 使用 **getData()** 方法獲取 XYChart.Series 類的可觀察列表。

  • 使用 **add()** 或 **addAll()** 方法將建立的資料點新增到列表中。

  • 將建立的資料系列新增到面積圖中,如下所示 -

areachart.getData().add(series);

示例

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.AreaChart;
import javafx.stage.Stage;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.StackPane;
public class AreaChartExample extends Application {
   public void start(Stage stage) {
      //Defining the X and Y axes
      NumberAxis xAxis = new NumberAxis();
      NumberAxis yAxis = new NumberAxis(); …
      //Setting labels to the axes
      xAxis.setLabel("Months");
      yAxis.setLabel("Rainfall (mm)");
      //Creating the Area chart
      AreaChart<String, Number> areaChart = new AreaChart(xAxis, yAxis);
      //Prepare data for the area chart
      XYChart.Series series = new XYChart.Series();
      series.getData().add(new XYChart.Data(1, 13.2));
      series.getData().add(new XYChart.Data(2, 7.9));
      series.getData().add(new XYChart.Data(3, 15.3));
      series.getData().add(new XYChart.Data(4, 20.2));
      series.getData().add(new XYChart.Data(5, 35.7));
      series.getData().add(new XYChart.Data(6, 103.8));
      series.getData().add(new XYChart.Data(7, 169.9));
      series.getData().add(new XYChart.Data(8, 178.7));
      series.getData().add(new XYChart.Data(9, 158.3));
      series.getData().add(new XYChart.Data(10, 97.2));
      series.getData().add(new XYChart.Data(11, 22.4));
      series.getData().add(new XYChart.Data(12, 5.9));
      //Setting the name to the line (series)
      series.setName("Rainfall In Hyderabad");
      //Setting data to the area chart
      areaChart.getData().addAll(series);
      //Creating a stack pane to hold the chart
      StackPane pane = new StackPane(areaChart);
      //Setting the Scene
      Scene scene = new Scene(pane, 595, 300);
      stage.setTitle("Area Chart");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於: 2020年5月19日

140 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.