gpt4 book ai didi

JavaFX "is already set as root of another scene"

转载 作者:行者123 更新时间:2023-12-01 19:23:06 26 4
gpt4 key购买 nike

我想在两个场景之间交换。例如,第一个按钮有一个带有文本“Go to Stage 2”的按钮,第二个按钮有一个带有文本“Go Back”的按钮。现在的问题是,我可以使用按钮进入第 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);
}
}

最佳答案

我认为异常(exception)是非常明显的,每次切换场景时,您都会在多个场景中放置相同的根。因此,您可以在开始时创建场景并在它们之间切换:

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

关于JavaFX "is already set as root of another scene",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com