java - 在 JavaFX 场景和非 JavaFX 场景之间切换

标签 java user-interface javafx fxml

我创建了一个游戏,想为其添加一个开始屏幕,我使用 FXML 添加了它,并添加了 2 个按钮(开始和退出)。

按下开始按钮后,我希望游戏加载并将场景切换到游戏开始。我对如何做到这一点有一个粗略的想法,但我有点挣扎,因为我的 SampleController 类不知道有关启动游戏等的任何信息,因为所有这些代码(以及加载初始的代码)开始菜单)在我的主类中,所以这是我尝试过的事情:

@FXML
void startGame(ActionEvent event) {
    background.start();
    primaryStage.setScene(scene);
    start();
}

我尝试使用切换场景的功能来做到这一点,但它不起作用,还尝试使用Stage window = (Stage)((Node)event.getSource()).getScene().getWindow();获取有关舞台的信息。正如我从 YouTube 视频中看到的一个可能的解决方案,但它告诉我 Node 无法解析为类型。

这是我的代码:

主要

public class Main extends Application 
{
AnimationTimer timer;
MyStage background;
Animal animal; //This is the player/frog that is moved

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) throws IOException {
    Parent root = FXMLLoader.load(getClass().getResource("/fxml/startMenu.fxml"));
    primaryStage.setScene(new Scene(root));
    primaryStage.setTitle("Game");
    primaryStage.show();

    //All the code after this point is essentially what I want to be executed upon pressing the button
    background = new MyStage();
    Scene scene  = new Scene(background,600,800);
    BackgroundImage froggerback = new BackgroundImage("file:resources/froggerBackground.png");
    background.add(froggerback);


    //At this point, a bunch of code like the line below is called to add in the different obstacles to the background
    background.add(new Turtle(500, 376, -1, 130, 130));


    //background.start();
    //primaryStage.setScene(scene);
    //primaryStage.show();
    //start();
}

示例 Controller 类

public class SampleController {

@FXML
private Button quitButton;

@FXML
private Button startButton;

@FXML
void startGame(ActionEvent event) {

}

@FXML
void quitGame(ActionEvent event) {

}

感谢任何帮助。

谢谢。

最佳答案

假设:

  1. 您的 SampleController 是链接游戏的 startButton 的 FXML Controller 。
  2. 在 SampleController 中,您为开始按钮 startGame 定义了一个操作事件处理程序。
  3. 您还为游戏布局定义了另一个 FXML 文件,名为 game.fxml

然后,您可以从开始按钮获取当前场景,并将场景的根替换为加载game.fxml时派生的新父场景:

@FXML
private Button startButton;

@FXML
void startGame(ActionEvent event) {
    Parent gameRoot = FXMLLoader.load(
        getClass().getResource("game.fxml")
    );
    startButton.getScene().setRoot(gameRoot); 
}

您不需要创建新的场景或舞台(除非您出于其他原因确实想要这样做)。如果您确实需要这样做(您可能不需要),那么这超出了我在此答案中提供的范围。

关于java - 在 JavaFX 场景和非 JavaFX 场景之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59077832/

相关文章:

java - 检查网络和互联网连接 - Android

java - 打开启动 Swing 界面的首选方法是什么?有什么区别?

Java - 处理大型 GUI 构造函数的最佳方法?

java - 如何获得 JavaFX 应用程序中的主要阶段?

java - 确定用户的首选语言

java - 为什么 Java 允许在旧值和新值均为 null 时触发属性更改

Java套接字swingWorker正在运行但没有接收或传输消息

user-interface - 如何在 React-Native-Elements 中使用 Ant Design Icon

JavaFx:TreeTableView 箭头引用

Javafx 点击一个圆圈并获取它的引用