Search code examples
javajavafxlinechartscenegridpane

Can I include a JavaFX LineChart in a JavaFX GUI


I would like to declare a JavaFX GridPane of two panels, the left one containing a push button. When the push button is clicked a LineChart is displayed in the right hand panel. The coding would presumably look like this:

public class FormLineChart extends Application {

    @Override 
    public void start(Stage stage) {
        stage.setTitle("A Title");
        //Create the grid for defining the GUI
        GridPane grid = new GridPane();
        // add gui objects to grid
        ...
        //Create the chart
        final LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
        ...
        // Create the series and display the lineChart
        lineChart.getData().add(series);
        stage.setScene(scene);

        Scene scene = new Scene(grid, 427, 319);
        //How do we add 'lineChart' to scene as well as keeping 'grid'?
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Specifically is it possible to combine 'grid' and 'lineChart' in one scene? At the moment only the GUI is displayed because on is forced to set the scene to the grid.


Solution

  • As @James_D said you simply need another container to achieve that. A Pane can contain GUI controls as well as another Pane.

    In the example below I put a GridPane with few buttons inside a BorderPane that divides the window into right and left part.

    @Override
    public void start(Stage stage) {
        stage.setTitle("A Title");
    
        // Root element
        BorderPane root = new BorderPane();
    
        // GridPane
        GridPane grid = new GridPane();
        grid.setPadding(new Insets(10,10,10,10));
        grid.setVgap(10);
        grid.add(new Button("Button 1"), 0, 0);
        grid.add(new Button("Button 2"), 0, 1);
        grid.add(new Button("Button 3"), 0, 2);
    
        // Chart
        final NumberAxis xAxis = new NumberAxis();
        final NumberAxis yAxis = new NumberAxis();
        final LineChart<Number, Number> lineChart = new LineChart<>(xAxis, yAxis);
        XYChart.Series series = new XYChart.Series();
        series.setName("Chart");
        series.getData().add(new XYChart.Data(1, 5));
        series.getData().add(new XYChart.Data(2, 10));
        lineChart.getData().add(series);
    
        root.setLeft(grid);
        root.setRight(lineChart);
    
        Scene scene = new Scene(root, 600, 300);
    
        stage.setScene(scene);
        stage.show();
    }