JavaFX,Label仅在调整窗口大小后显示

时间:2017-12-07 08:01:16

标签: java user-interface javafx resize

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

以下是一个简单的Minimal,Complete和Verifiable示例:

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

1 个答案:

答案 0 :(得分:-1)

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