I've been reading a lot of SO answer and questions but I never asked anything before.
My question is about desing patterns and best practices in Swing application.
Suppose you have a Swing application with a GUI class with a JLabel and another class (not an inner class of the previous) which extends Thread and perform some network operations (basically it periodically fetch resources from a web API to check if a given value appear).
When a certain value is fetched by the second class I need to update the JLabel of the firt class. I'm perfectly aware this should be done in the EDT using invokeLater()
, my question is how to handle the access from the background Thread to the JLabel.setText() method.
As far as I know I see three solution:
- provide a static getter in the GUI class and call it insite a
SwingUtilities.invokeLater()
in the Thread class - provide a static method inside the GUI class which internally calls
SwingUtilities.invokeLater()
and access that method (say MyGui.updateTheLabel()) from the Thread class - passing a reference of the JLabel to the Thread constructor and use that reference to update the label with SwingUtilities.invokeLater()
Which one of this solution is better? Are there particular design patterns meant to solve this issue. I find it ugly to put SwingUtilities.invokeLater() everywhere I want to update the GUI or creating static getters around.
Thank you :)