Javafx使用Platform.RunLater从另一个线程更新TextArea



我正在尝试使用实现Runnable的另一类使用Platform.runLater更新TextArea。我在一堂课中都有所有的GUI(在某个地方,我的Textarea所在),我创建new server线程并在创建GUI时运行它。我试图从Server线程中使用Platform.runLater来更新我的TextArea,但Platform.runLater无法到达我的textarea。

public class SimulationWindow {
    public SimulationWindow instance() {
        return this;
    }
    public static void DisplaySimulationWindow() throws FileNotFoundException {
        Stage SimuStage = new Stage();
        SimuStage.initModality(Modality.APPLICATION_MODAL);
        SimuStage.setTitle("Simulation Window");
        Server myServer = new Server(instance());
        Thread serverThread = new Thread(myServer);
        serverThread.start();
        TextArea serverTextArea;
         .
         .
         .
}
public class Server implements Runnable {
    @Override
    public void run() {
        while(true){
            whileConnected();
        .
        .
    }
    private void whileConnected() throws IOException {
        sendMessage(message);
        do {
            try {
                message = (String) input.readObject();  
                showMessage(message);
                .
                .
                .
    }
   private void showMessage(String x) {
    Platform.runLater(() -> serverTextArea.appendText(x));          
   }

我尝试将模拟Window的实例传递给服务器构造函数,就像他们在这里一样:从不同类中的不同线程修改Javafx GUI

但是,java不会让我的仿真窗户实例作为服务器约束的参数。其他解决方案将Hold Server和SimulationWindow类是一个,但我想保持它们分开。任何提示都将不胜感激!

i按照Kleopatra的建议解决了这一点。我通过了我的服务器构造函数的Textarea。我想从GUI类中更新我的GUI中的Textarea,以及从服务器类中的客户端获取消息时。(我在Simuwindow())内创建并启动服务器

public class myGUI{
    public void SimuWindow(){
        //this method creates all the GUI.
        Server myServer = new Server(serverTextArea);
        Thread serverThread = new Thread(myServer);
        serverThread.start();
        sendingTest = new TextField();
        sendingTest.setPromptText("test communication here");
        sendingTest.setOnAction(event -> {
        String message = new String ("nServer says: ");
        message = message + sendingTest.getText();
        serverTextArea.appendText(message);
        myServer.sendMessage(message);
        sendingTest.clear();
    });
    }
}
public class Server implements Runnable{
    //This is my server class that connects and listens to clients
    TextArea mytextArea;
    public Server(TextArea x) {
        this.mytextArea = x;
    }
    private void whileConnected() throws IOException {          
    do {
        try {
            message = (String) input.readObject();  
            showMessage(message);               
        }catch(ClassNotFoundException classNotFoundException) {
            System.out.println("n i dont know the message");
        }
    }while(!message.equals("Disconnected"));    
    private void showMessage(String mess) {
            Platform.runLater(() -> mytextArea.appendText(mess));           
    }
}

我在客户班上也做了同样的事情。感谢您的帮助。

最新更新