JavaFX "is already set as root of another scene"

JavaFX "is already set as root of another scene"

我想在两个场景之间切换。 比如,第一个有一个带有文本 "Go to Stage 2" 的按钮,第二个有一个带有文本 "Go Back" 的按钮。 现在,问题是,我可以使用按钮进入第 2 阶段,但无法返回。原因是:"already set as root of another scene"。 对我来说听起来很简单,但我就是不知道如何解决这个问题。

我知道我不是第一个遇到这个问题的人,但我找不到答案...请发送帮助!

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

我觉得异常很明显,你每次切换场景的时候都是把同一个root放在多个场景中。所以你可以在开始时创建你的场景并在它们之间切换:

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