[英]Can't edit non-static text area in Javafx Application class from other class
I'm trying to implement a GUI in JavaFX for a text-based game I've been making. 我正在尝试为我一直在做的基于文本的游戏在JavaFX中实现GUI。
This part of the main class sets everything up: 主类的这一部分设置了所有内容:
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();
I use a FXML-file generated from SceneBuilder and Main is the controller. 我使用从SceneBuilder生成的FXML文件,并且Main是控制器。 It works well and when I tried to set some text to input through the initialize function, the text printed fine (but I have now removed that method).
它运行良好,当我尝试设置一些文本以通过initialize函数输入时,该文本可以很好地打印(但是我现在已经删除了该方法)。
The problem comes when I then launch my Game-class and try to print text from it to the text area "Input" in main. 问题出在我随后启动我的游戏类并尝试将其中的文本打印到main中的文本区域“ Input”时。
I use this method in Main to set the text: 我在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());
}
This method should work, the problem I have is that I don't know how to call it from the Game-class. 这种方法应该可行,我的问题是我不知道如何从游戏类中调用它。 Since the Main class isn't instantiated I can't call on a Main-object and I can't make the text area static as that doesn't work with JavaFx applications.
由于没有实例化Main类,因此无法调用Main对象,也无法使文本区域静态,因为JavaFx应用程序无法使用该文本区域。
So how do I go about to call the "printGameInfo" from a separate class to set some strings to a text area? 那么,如何从一个单独的类中调用“ printGameInfo”,以将一些字符串设置到文本区域?
Thanks a lot! 非常感谢!
The Main class definitely is instantiated or how should anything be able to call its start method which is not static? Main类肯定是实例化的,或者什么应该能够调用非静态的start方法呢? When you instantiate your Game class you could pass it a reference to your Main class instance.
实例化Game类时,可以将其传递给Main类实例的引用。 Nevertheless this is an awfull software design.
但是,这是一个糟糕的软件设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.