Monday, June 27, 2016

83. LineChart

LineChart is very similar to the ScatterChart except each series is connected with lines.


The only thing changed here, from example 82, is that we use the LineChart class instead of ScatterChart class, and rename the resulting object to lineChart.


package ex83;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
 
public class Ex83 extends Application {
 
    ObservableList<XYChart.Series<Integer, Double>> obList 
            = FXCollections.observableArrayList();
    
    public static void main(String[] args) {
        launch(args);
    }
 
    @Override
    public void start(Stage primaryStage) {
        NumberAxis xAxis = new NumberAxis();
        xAxis.setAutoRanging(false);
        xAxis.setLowerBound(-1);
        xAxis.setUpperBound(3);
        xAxis.setTickUnit(1);
        NumberAxis yAxis = new NumberAxis();
        initData();
        LineChart lineChart = new LineChart(xAxis, yAxis, obList);
        lineChart.setVerticalZeroLineVisible(false);
        lineChart.setTitle("A line plot");
        
        StackPane root = new StackPane();
        root.getChildren().add(lineChart);
        
        primaryStage.setTitle("Example 83. LineChart");
        primaryStage.setScene(new Scene(root, 400, 250));
        primaryStage.show();
    }
 
    private void initData() {
        Series series1 = new Series<>();
        Series series2 = new Series<>();
        series1.getData().addAll(
                new XYChart.Data(0, 5),
                new XYChart.Data(1, 3),
                new XYChart.Data(2, 2)
                );
        series1.setName("series 1");
        series2.getData().addAll(
                new XYChart.Data(0, 2),
                new XYChart.Data(1, 4),
                new XYChart.Data(2, 7)
                );
        series2.setName("series 2");
        obList.addAll(series1, series2);
    }
}

This is the output:


No comments:

Post a Comment