javafx 中的图表和按钮不呈现

chart and Button in javafx doesn't render

我想在屏幕上呈现一组按钮,然后呈现一个饼图。我几乎尝试了所有可能的方法,但似乎有些方法不起作用。可以单独渲染按钮数组(usercontrol())或饼图(图形)但是当我尝试同时执行这两种操作时它只渲染 buttons.plz 的数组,不用担心 return 类型的函数.任何帮助将不胜感激。

public class Layout {

    // returns Windows height and width
    private final double width = 600;
    private final double height = 400;

    private Button[] userControl() { // navigation bar buttons
        Button[] buttons = new Button[3];

        buttons[0] = new Button("BUY Share!"); // Buy shares buttons
        buttons[0].setLayoutX(width - 100);
        buttons[0].setLayoutY(10);
        buttons[1] = new Button("Sell Shares!"); // Sell shares buttons
        buttons[1].setLayoutX(width - 200);
        buttons[1].setLayoutY(10);
        buttons[2] = new Button("Show Share"); // Show shares buttons
        buttons[2].setLayoutX(width - 300);
        buttons[2].setLayoutY(10);
        return buttons;
    }

    public void pie() {
        ObservableList<PieChart.Data> shareHolders
                = FXCollections.observableArrayList(
                        new PieChart.Data("user1", 13),
                        new PieChart.Data("user2", 25),
                        new PieChart.Data("user3", 10),
                        new PieChart.Data("user4", 22),
                        new PieChart.Data("user5", 30));
        PieChart chart = new PieChart(shareHolders);
        chart.setTitle("Share Holders Shares");
        VBox pie = new VBox();
        pie.setLayoutY(100);
        pie.getChildren().addAll(chart);
        pane().getChildren().add(pie);
        // return pie;
    }

    private Pane pane() {
        Pane pane = new Pane();

        pane.getChildren().addAll(userControl());
        return pane;
    }

    public Stage window() {

        //pane().getChildren().add();
        pie();
        Scene scene = new Scene(pane(), 600, 400);
        Stage primaryStage = new Stage();
        primaryStage.setScene(scene);
        primaryStage.setTitle("ShareHolders!");
        primaryStage.show();
        return primaryStage;
    }

}

您的问题是每次调用 pane 方法时都会创建一个新的 Pane。您需要更改它,也许可以使用全局 Pane 对象。

//First, declare a global Pane.
static Pane pane = new Pane();

//Make your pie() method return the pie VBox.
public VBox pie() {
    /*Blah blah blah, making the pie...*/
    return pie//Remember, pie is a VBox, which is why we are returning the VBox.
}

//Later, when you build your window, add the pie and the buttons to the GLOBAL PANE...
public Stage window() {
    pane.getChildren().add(pie());      //...right here.
    pane.getChildren().addAll(userControl());
    /*Build the primary stage...*/
    return primaryStage;
}

这应该会得到您想要的结果。