Hi guys,
I'm developing a small app, which would have Swing GUI. App is doing IO task in another thread, when that thread finishes GUI should be updated acordingly to reflect thread's operation result. Class running in a (worker, non-GUI) has object passed to it in contructor which would be used for updating GUI, so I don't need to put GUI stuff in a non-GUI class, but rather pass object for updating GUI to that class.
As I understand form reading here, (thread/swing) safe options for updating (changing) Swing GUI would be to use javax.swing.SwingUtilities.invokeLater()
, javax.swing.SwingUtilities.invokeLaterWait()
and/or javax.swing.SwingWorker()
which basically are doing the same thing.
This all threading issue with Swing is a little confusing for me, and yet I need to use threads to do anything meaningful in GUI apps and not hung GUI while processing in EDT, so what interests me for now is this:
Are
invokeLater
andinvokeLaterWait
like sending message to EDT and waiting for it do it when it finishes processing messages that were before that call?is it correct from Swing thread safety aspect, to do something like this:
interface IUPDATEGUI { public void update(); } // in EDT/where I can access components directly class UpdateJList implements IUPDATEGUI { public void update() { // update JList... someJList.revalidate(); someJList.repain(); } } class FileOperations implements Runnable { private IUPDATEGUI upObj; List<File> result = new ArrayList<File>; // upObject is accessing this public void FileOperations(IUPDATEGUI upObj) { this.upObj = upObj; } private void someIOTask() { // ... // IO processing finished, result is in "result" } public void run() { someIOTask(); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { upObj.update(); // access result and update JList } }; ); } }
In case this isn't correct then how should this be done?
If I could, I would prefer to use invokeLater
instead of SwingWorker
if possible, because I wouldn't need to change my whole class and it's somehow more neat/distinct me (like sending a message in Win32 apps).
Thanks in advance.