无法在其他类中编辑Javafx应用程序类中的非静态文本区域

问题描述:

我正在尝试在JavaFX中为我一直在制作的基于文本的游戏实现GUI。无法在其他类中编辑Javafx应用程序类中的非静态文本区域

主类的这部分完成所有设置:

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文件是控制器。它工作的很好,当我试图设置一些文本通过初始化函数输入时,文本打印正常(但我现在已经删除了该方法)。

问题来了,当我然后启动我的游戏类,并尝试从它打印文本到主要文本区域“输入”。

我用这个方法主要设置文本:

/** 
* 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-object,也无法使文本区域变为静态,因为它不适用于JavaFx应用程序。

那么我该如何去从一个单独的类中调用“printGameInfo”来将一些字符串设置为文本区?

非常感谢!

+0

您应该阅读关于JavaFx控制器:http://code.makery.ch/library/javafx-8-tutorial/part2/ –

+0

如果'Main'类没有实例化,它不应该有实例成员。 – EJP

+0

不要使用'Application'类作为控制器类。首先为控制器创建一个单独的类,然后从那里开始。请参阅https://*.com/questions/33303167/javafx-can-application-class-be-the-controller-class和https://*.com/questions/32081713/javafx-controller-class-not-working –

Main类肯定是实例化的,或者应该如何能够调用它的非静态的start方法?当你实例化你的Game类时,你可以将它传递给你的Main类实例的引用。尽管如此,这是一个很好的软件设计。

+0

这是一个糟糕的软件设计?我只是想改进,所以我很乐意提供关于如何编写更好的代码的反馈。 –