I have a java class that handles serial port communications (SerialIO.class). It initializes the port, spurns off a thread that endlessly loops and listens to the port and implements a write method to write strings to the port.
I have the listening thread, reading until it receives a ’
', at that point I need it to send the string to the GUI (the GUI initialized the SerialIO.class). What would be the proper method to do this? A custom listener in the GUI? Can I pass that listener to the serialIO class to fire it?
Or should I have my reading thread in the GUI (it already utilizies an event when it detects a read in the port)?
BTW, I’m using rxtx – http://www.rxtx.org – to handle the serial port stuff.
The important thing to remember with Swing is that you want all updates to GUI components to be handled in the event-dispatch thread (EDT); conversely, you want all other action to happen in some other thread. Typically, if you or the component you’re using has implemented the dispatching of a custom event properly, the code in any of that event listener implementation’s methods will be executed in the EDT.
So if you receive an event via a listener and want to launch the serial process, you’d launch it in a separate thread, which it sounds like you’ve done. If you then want to update a GUI component from that separate thread, you need to fire an event and use its listener, whose code will be executed in the EDT, to update the component.
But most of the Swing components come with models, which basically provide a shortcut to this whole process. For instance, whern you add a row to a javax.swing.table.DefaultTableModel, it fires an event to tell the javax.swing.JTable component to refresh the display. So it’s generally safe to use the default models to update components from user threads.
Bottom line: if you’re performing any operation on a Component, make sure it’s being done in the EDT. A simple way to verify that this is happening: just before the code that operates on a Component, call javax.swing.SwingUtilities.isEventDispatchThread() to make sure the listener code is being notified properly.