我想在两个场景之间切换。同样,第一个按钮带有文本“ Go to Stage 2”,第二个按钮带有文本“ Go Back”。现在的问题是,我可以使用Button进入第2阶段,但是我不能返回。原因是:“已经设置为另一个场景的根”。对我来说听起来很简单,但我只是不知道如何解决该问题。
我知道我不是第一个遇到问题的人,但是我找不到答案...请发送帮助!
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
BorderPane root1 = new BorderPane();
BorderPane root2 = new BorderPane();
primaryStage.setTitle("Hello World");
Button nextStageButton = new Button("Go to Stage 2");
root1.setCenter(nextStageButton);
nextStageButton.setOnAction((event) -> {
primaryStage.setScene(new Scene(root2, 300, 275));
});
Button backStageButton = new Button("Go Back");
root2.setCenter(backStageButton);
backStageButton.setOnAction((event) -> {
primaryStage.setScene(new Scene(root1, 300, 275));
});
primaryStage.setScene(new Scene(root1, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我认为例外非常明显,每次切换场景时,您都会在多个场景中使用相同的根。因此,您可以在开始时创建场景并在它们之间切换:
@Override
public void start(Stage primaryStage) throws Exception{
BorderPane root1 = new BorderPane();
BorderPane root2 = new BorderPane();
primaryStage.setTitle("Hello World");
Button nextStageButton = new Button("Go to Stage 2");
root1.setCenter(nextStageButton);
Scene scene1 =new Scene(root1, 300, 275);
Scene scene2 =new Scene(root2, 300, 275);
nextStageButton.setOnAction((event) -> {
primaryStage.setScene(scene2);
});
Button backStageButton = new Button("Go Back");
root2.setCenter(backStageButton);
backStageButton.setOnAction((event) -> {
primaryStage.setScene(scene1);
});
primaryStage.setScene(scene1);
primaryStage.show();
}
或者您可以创建一个场景并在根之间切换:
@Override
public void start(Stage primaryStage) throws Exception{
BorderPane root1 = new BorderPane();
BorderPane root2 = new BorderPane();
primaryStage.setTitle("Hello World");
Button nextStageButton = new Button("Go to Stage 2");
root1.setCenter(nextStageButton);
Scene scene =new Scene(root1, 300, 275);
nextStageButton.setOnAction((event) -> {
scene.setRoot(root2);
});
Button backStageButton = new Button("Go Back");
root2.setCenter(backStageButton);
backStageButton.setOnAction((event) -> {
scene.setRoot(root1);
});
primaryStage.setScene(scene);
primaryStage.show();
}