JavaFX: Line and bar chart

When it comes to setting up the bar or line chart, there are a few classes that we can use in JavaFX.  JavaFX provides the line and bar chart objects and in addition, it provides the numberAxis for the x-y axis and also XYChart for plotting the positions of line and bar.

package javafxapplication4;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class JavaFXApplication4 extends Application {


    @Override
    public void start(Stage stage) {

        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        final CategoryAxis cXAxis = new CategoryAxis();

        
        //Declarations of the 2 types of charts
        final BarChart<String, Number> bc = new BarChart<>(cXAxis, yAxis);
        final LineChart<Number, Number> lc = new LineChart<>(xAxis, yAxis);

        //setting up the bar chart
        XYChart.Series series1 = new XYChart.Series();
        series1.getData().add(new XYChart.Data("A", 200));
        series1.getData().add(new XYChart.Data("B", 50));

        //setting up the line chart
        XYChart.Series series2 = new XYChart.Series();
        series2.getData().add(new XYChart.Data(10, 210));
        series2.getData().add(new XYChart.Data(3, 35));

        bc.getData().addAll(series1);
        lc.getData().addAll(series2);

        Pane pane = new Pane();
        pane.getChildren().add(lc);
        pane.getChildren().add(bc);

        bc.setOpacity(0.5);
        
        Scene scene = new Scene(pane, 500, 400);
        stage.setScene(scene);
        stage.show();
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}

chart

Series Navigation<< JavaFX: Media player
JavaFX: Drawing a 3D sphere >>