2

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?

Karim Harazin
  • 1,463
  • 2
  • 16
  • 34

2 Answers2

4

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:

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I will read more about EDT. what are the consequences of updating outside of EDT? – Karim Harazin Feb 20 '16 at 19:18
  • @developer: you risk unexpected intermittent null pointer exceptions, race conditions, and any and all other threading issues. Please check out the links added to answer. – Hovercraft Full Of Eels Feb 20 '16 at 19:20
  • 1
    @developer, the only consequence you need to worry about is, if you break the rules (e.g., if you call a Swing method from a non-EDT thread), then you've got nothing to complain about if it doesn't work. You can't always predict what will go wrong when a program breaks rules about multi-threading. An incorrect program might work on one platform, might misbehave on another platform, and might misbehave in a different way on a third platform. – Solomon Slow Feb 20 '16 at 22:20
0

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.