我是与Javafx合作的新手,问题是,在更改场景之后,并非所有组件都被外交。例如,我有一个烤面包,将添加到Borderpane中心,并将标签添加到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);
}
}
}
}
我无法再现您的问题,因为您的代码对我来说很好。但是您的组件可能会缩小太多,以至于没有渲染。为避免这种情况,请尝试使用前缀的最小宽度和高度。