Reputation: 1473
I am working on a project for receiving data from client sockets. The user interface contains a Text Area to show the received data.
What is the best way to pass the received data from the servers threads back to text area?
Currently what i do is the following.
jtextarea.setText(newMessage);
Is my approach correct?
Upvotes: 2
Views: 2343
Reputation: 29
For a more dedicated action processing example, please look at https://github.com/greggwon/Ham and specifically at the code in https://github.com/greggwon/Ham/blob/master/SwingUtil/src/org/wonderly/swing/ComponentUpdateThread.java for a concrete example of how to deal with swing component updates. This class provides a "before", "during" and "after" functional behavior all run in the appropriate thread so that you can do swing component updates without worrying about which thread is needed and having to create all the threads and runnables yourself.
Upvotes: 0
Reputation: 285405
No, number 4 is wrong since you're changing the state of a Swing component off of the EDT, the Swing event thread. Either wrap jtextarea.setText(newMessage);
inside of a Runnable and queue it on the Swing event thread via: SwingUtilities.invokeLater(Runnable r)
, or use a SwingWorker for your background thread and use the publish/process method pair to update your Swing GUI from the background thread.
Please check out:
Upvotes: 4