我正在尝试在JavaFX中为我一直在制作的基于文本的游戏实现GUI。
主类的这一部分设置了所有内容:
public class Main extends Application{
@FXML
protected TextField input;
@FXML
protected TextArea output, inventory, commands;
protected static List<String> history;
protected static int historyPointer;
protected static String textToRead = null;
private Service<Void> backgroundThread;
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("Console.fxml"));
BorderPane root = (BorderPane) loader.load();
history = new ArrayList<>();
historyPointer = 0;
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("MyConsoleFXGUI"); //Could later be changed so that the actual game title is displayed here.
stage.show();
我使用从SceneBuilder生成的FXML文件,Main是控制器。它运行良好,当我尝试通过初始化函数设置一些文本以输入时,文本打印良好(但我现在已经删除了该方法(。
当我启动我的游戏类并尝试将文本从它打印到主文本区域"输入"时,问题就来了。
我在 Main 中使用此方法设置文本:
/**
* Called when the game wants to print something to the game
* @param message The text to be printed to the console.
*/
public void printGameInfo(String message) {
System.out.println("This method was attempted!");
output.setText(message + System.lineSeparator());
}
这种方法应该有效,我遇到的问题是我不知道如何从游戏类调用它。由于 Main 类未实例化,我无法调用 Main-对象,也无法使文本区域成为静态,因为这不适用于 JavaFx 应用程序。
那么我该如何从单独的类中调用"printGameInfo"以将一些字符串设置为文本区域呢?
多谢!
Main 类肯定是实例化的,或者有什么东西可以调用它不是静态的 start 方法?当您实例化游戏类时,您可以向它传递对 Main 类实例的引用。然而,这是一个糟糕的软件设计。