----修订草稿----JavaFX - 如何将一个变量从控制器发送到Main类?
我一直在尝试使用JavaFX创建游戏。在游戏中,玩家首先看到菜单页面(“玩游戏”,“选项”,“出口”等),然后他/她点击“OnlineGame”按钮开始游戏。
现在我已经有一个菜单(使用fxml创建)及其控制器。
<!-- MainMenu.fxml -->
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.media.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.effect.*?>
<?import java.lang.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainMenuController">
<children>
<Button fx:id="OnlineGame" layoutX="55.0" layoutY="157.0" mnemonicParsing="false" onAction="#OnlineGame" opacity="0.6" prefHeight="51.0" prefWidth="229.0" text="Play Online Game" textFill="#2067a1">
<font>
<Font size="21.0" />
</font>
</Button>
</children>
</AnchorPane>
控制器:
import *****;
//MainMenuController.java
public class MainMenuController{
@FXML private Button OnlineGame;
@FXML protected void OnlineGame(ActionEvent event) throws IOException{
//start the game
}
}
菜单中Main.start初始化,它工作得很好。
import *****;
public class Main extends Application {
public void start(Stage Stage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("MainMenu.fxml"));
Scene scene = new Scene(root,730,439); //set SceneSize
Stage.setScene(scene);
Stage.show();
//call three methods to start a game
prepareGame();
addHandlers(scene);
startGame();
} catch(Exception e) {
e.printStackTrace();
}
}
private void prepareGame(){**********}
private void addHandlers(Scene scene){***********}
private void startGame(){****}
public static void main(String[] args) {
launch(args);
}
不过,我也有一些Main.start方法来初始化游戏(prepareGame(); addHandlers(场景); startGame();)。正如你所看到的,我还需要在stage.show;之后放置它们。所以现在问题是,当我运行我的程序时,这三种方法立即运行(在我点击菜单中的“OnlineGame”按钮之前!)。
那么有什么方法可以实现我的目标(即玩家在点击“OnlineGame”后会看到游戏页面)? PS:我简化了我的代码,使我的问题变得简短(尽管它仍然很长:-D)。我不是母语的人,所以如果我的话很混乱,请让我知道,以便我可以再次解释。更重要的是,如果需要,我想发布更多细节。
在此先感谢!
我想直接在Gamecontroller.java中调用这三种方法,但它不起作用,因为我需要在addHandlers(场景)中有“场景”; 。由于某些原因,我无法将它们设置为静态方法 –
在我提供了答案后,您完全更改了此问题。 –
嗨James_D!感谢您的回答,我不知道我的控制器中可能有监听器,所以我添加了我的评论。现在我会尝试一下,并告诉你它是否有效!顺便说一句,抱歉我的误导! –