如何从另一个创建线程以启动GUI的应用程序更新TextArea?

时间:2019-05-02 12:52:14

标签: multithreading javafx fxml

我正在设置一个服务器,该服务器使用线程启动GUI,在其中我想更新TextArea,从而创建一种Log:当客户端连接或执行某项操作时,但我无法更新GUI 。我尝试过的每种方式都得到NullPointerException

试图通过一些方法来获得控制器,但是没有运气

服务器代码

public class Server{

    public static void main(String[] args) throws IOException{
        Thread l = new Thread(){
            public void run(){
                javafx.application.Application.launch(Logger.class);
            }
        };
        l.start();
        ServerSocket server = new ServerSocket(8189);
            while(true){
               Socket s = null;
            try{
                s = server.accept();

                ObjectInputStream input = new 
                ObjectInputStream(s.getInputStream());
                ObjectOutputStream output = new 
                ObjectOutputStream(s.getOutputStream());

                Thread t = new ClientHandler(s, input, output);
                t.start();
            }catch(IOException e){
                s.close();
                System.out.println(e.getMessage());
            }
            }
        }

}

控制器代码

public class Controller implements Initializable{

    @FXML
    public TextArea log = new TextArea();

    public void logger(String s){
        log.appendText(s);
    }

    @Override
    public void initialize(URL url, ResourceBundle rb){
        log.setText("Log has started...");
    } 

}

1 个答案:

答案 0 :(得分:0)

出现NullPointerException的原因是此行

@FXML
public TextArea log = new TextArea();

它已经在FXML中初始化,所以只需

@FXML
public TextArea log;