我创建了一个游戏,想为其添加一个开始屏幕,我使用 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) {
}
感谢任何帮助。
谢谢。
最佳答案
假设:
- 您的
SampleController
是链接游戏的startButton
的 FXML Controller 。 - 在 SampleController 中,您为开始按钮
startGame
定义了一个操作事件处理程序。 - 您还为游戏布局定义了另一个 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/