JavaFX,标签仅在 window 调整大小后显示

JavaFX, Label only showing after resizing of the window

我刚开始使用 JavaFX,问题是,在更改场景后,并非所有组件都显示出来。例如,我有一个 GridPane,它将被添加到 BorderPane 中心,一个 Label 将被添加到 BorderPane 的底部。但是在我改变场景后这个标签没有显示,只有在调整大小后它才有效。

以下是一个简单的最小、完整且可验证的示例:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.scene.Scene;

public class View extends Application implements EventHandler<ActionEvent> {
    private Scene scene1, scene2;
    private Button b1, b2;
    private Stage stage;

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

    @Override
    public void start(Stage stage) throws Exception {
        this.stage = stage;

        this.createScene1();
        this.stage.setScene(this.scene1);

        this.stage.setWidth(200);
        this.stage.setHeight(200);
        this.stage.show();
    }

    public void createScene1() {
        BorderPane border = new BorderPane();
        GridPane root = new GridPane();

        root.add(new Label("Scene 1"), 0, 0);
        this.b1 = new Button("Change to Scene 2");
        this.b1.setOnAction(this);
        root.add(this.b1, 0, 1);

        border.setCenter(root);
        border.setBottom(new Label("Should be visible"));
        this.scene1 = new Scene(border);
    }

    public void createScene2() {
        BorderPane border = new BorderPane();
        GridPane root = new GridPane();

        root.add(new Label("Scene 2"), 0, 0);
        this.b2 = new Button("Change to Scene 1");
        this.b2.setOnAction(this);
        root.add(this.b2, 0, 1);

        border.setCenter(root);
        border.setBottom(new Label("Should be visible"));
        this.scene2 = new Scene(border);
    }

    @Override
    public void handle(ActionEvent e) {
        if (this.b1 != null) {
            if (this.b1 == e.getSource()) {
                this.createScene2();
                this.stage.setScene(this.scene2);
            }
        }
        if (this.b2 != null) {
            if (this.b2 == e.getSource()) {
                this.createScene1();
                this.stage.setScene(this.scene1);
            }
        }
    }
}

我无法重现您的问题,因为您的代码对我来说工作正常。 但是您的组件可能会缩小很多,以至于无法渲染。为避免这种情况,请尝试使用带前缀的最小宽度和高度。