如何使用JavaFX建立折線圖?


內聯圖表,資料值表示由線連線的一系列點。在JavaFX中,您可以透過例項化**javafx.scene.chart.LineChart類**來建立折線圖。

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

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

設定資料

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

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

因此,要為折線建立資料:

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

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

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

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

  • 將建立的資料序列新增到折線圖中:

linechart.getData().add(series);

示例

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.StackPane;
public class LineChartExample extends Application {
   public void start(Stage stage) {
      //Defining the x and y axes
      NumberAxis xAxis = new NumberAxis();
      NumberAxis yAxis = new NumberAxis();
      //Setting labels for the axes
      xAxis.setLabel("Months");
      yAxis.setLabel("Rainfall (mm)");
      //Creating a line chart
      LineChart linechart = new LineChart(xAxis, yAxis);
      //Preparing the data points for the line1
      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 the data to Line chart
      linechart.getData().add(series);
      //Creating a stack pane to hold the chart
      StackPane pane = new StackPane(linechart);
      //Setting the Scene
      Scene scene = new Scene(pane, 595, 350);
      stage.setTitle("Line Chart");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於:2020年5月19日

429 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告