Java SwingWorker - using publish/process to update a TextArea in EDT?

╄→尐↘猪︶ㄣ 提交于 2019-12-11 06:53:39

问题


I had just coded a Swing program that starts up a SwingWorker (which runs a Socket Server). I have a JTextArea on the Swing GUI which gets updated with the data received by the Socket Server, using a JTextArea.append(String).

Is it the correct/threadsafe way to update a JTextArea on the Swing GUI? What about using publish/process?


回答1:


SwingWorker is usually used for one time long running processes (anything that will take more than a few milliseconds to complete). If you have persistent connection, it would be more appropriate to use a dedicated ExecutorService which will run the process, then when you want to update a swing component call

SwingUtilities.invokeLater(new Runnable() { 
    public void run() {
        .. update here
    }
}

The reason for this is SwingWorkers use a fixed thread pool size, so if you have a process that never completes than it limits the number threads other SwingWorkers can use concurrently



来源:https://stackoverflow.com/questions/6283297/java-swingworker-using-publish-process-to-update-a-textarea-in-edt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!