Karim Harazin
Karim Harazin

Reputation: 1473

Update Java Swing component from a background thread

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.

  1. start the JFrame Java Application
  2. Create a Server object and pass the JTextArea object to it.
  3. Start the socket server in a separate thread
  4. when new message received form a client, the thread update the JTextArea field like following

jtextarea.setText(newMessage);

Is my approach correct?

Upvotes: 2

Views: 2343

Answers (2)

Gregg Wonderly
Gregg Wonderly

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

Hovercraft Full Of Eels
Hovercraft Full Of Eels

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

Related Questions