【问题标题】:Can I include a JavaFX LineChart in a JavaFX GUI我可以在 JavaFX GUI 中包含 JavaFX LineChart
【发布时间】:2017-01-24 00:33:14
【问题描述】:

我想声明一个包含两个面板的 JavaFX GridPane,左边的一个包含一个按钮。单击按钮时,右侧面板中会显示一个 LineChart。编码大概是这样的:

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);
    }
}

特别是可以在一个场景中结合“网格”和“线图”吗?目前只显示 GUI,因为 on 强制将场景设置为网格。

【问题讨论】:

  • 将折线图和网格放在另一个窗格(某种)中,并使该窗格成为场景的根。或者,只需在按下按钮时将折线图添加到网格中的适当位置。
  • 其实就像grid.add(lineChart, 0,1);一样简单。您可以简单地将您的lineChart 直接添加到网格中

标签: java javafx linechart scene gridpane


【解决方案1】:

正如@James_D 所说,您只需要另一个容器即可实现这一目标。 Pane 可以包含 GUI 控件以及另一个 Pane

在下面的示例中,我将带有几个按钮的GridPane 放入了将窗口分成左右两部分的BorderPane

@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();
}

【讨论】:

  • 谢谢。效果很好。我对如何使用“root”来实现我需要的东西很模糊,现在它很清楚了。
猜你喜欢
  • 1970-01-01
  • 2012-08-03
  • 2017-06-16
  • 2013-01-14
  • 1970-01-01
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多