我已经创建了一个游戏,我想为其添加一个开始屏幕,我已经使用FXML以及一个添加了2个按钮(开始和退出)来添加了它。
按下开始按钮后,我希望游戏加载并切换场景到游戏开始。我对操作方法有一个大概的了解,但是我有点挣扎,因为我的SampleController类对启动游戏等一无所知,因为所有这些代码(以及加载初始代码的代码)开始菜单)位于我的Main类中,所以这是我尝试过的事情:
@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();
}
SampleControllerClass
public class SampleController {
@FXML
private Button quitButton;
@FXML
private Button startButton;
@FXML
void startGame(ActionEvent event) {
}
@FXML
void quitGame(ActionEvent event) {
}
感谢任何帮助。
谢谢。
答案 0 :(得分:0)
假设:
SampleController
是将startButton
链接到游戏的FXML控制器。startGame
定义了一个动作事件处理程序。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);
}
您不需要创建新的场景或舞台(除非出于某些其他原因您确实想这样做)。如果您确实需要这样做(您可能不需要这样做),那么那超出了我在此答案中提供的范围。