Re: EDT and SwingUtilities.invokeLater help
pek wrote:
OK, I got really confused about when to use SwingUtilities or not.
For example.
Let's say that I have a simple class that extends JFrame, a private
JButton field testButton and a private JLabel field testLabel.
Somewhere down the code I right the following:
testButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
testLabel.setText("testButton");
}
});
Does this needs to be converted to :
public void actionPerformed(ActionEvent e){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
testLabel.setText("testButton");
}
})
});
or not? And why..?
No. Event handlers (when invoked in response to actions in the GUI) are run by
the EDT. If you invoke the method manually from another thread then *that*
invocation should be wrapped in invokeLater().
When exactly do I need to use SwingUtilities?
Whenever you attempt to modify (and in most cases, read) any property of any
JComponent from a thread other than the EDT. Event handlers are a special case
because events are usually generated by user interaction with the GUI. The
event is handled by the EDT and the event handler which is invoked in response
to the event is run on the EDT.
If I have a thread that changes a JLabel inside/outside the class, do
I need it?
If the thread is not the EDT then, yes, you must use
SwingUtilites.invokeLater().
If the thread instead of changing the testLabel invokes
testButton.doClick(), will I still need to use SwingUtilities..?
I believe so, from my cursory glance at the doClick() method I see nothing which
would indicate that this method ensures that it is safe to call from a non-EDT
thread.
Overall, is there any good reference in the internet to explain all
these..?
The best starting place (at least in my opinion) is the Java Swing tutorial at
http://java.sun.com/docs/books/tutorial/uiswing/TOC.html
and the concurrency section of the Essential Classes tutorial:
http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html
--
Nigel Wade, System Administrator, Space Plasma Physics Group,
University of Leicester, Leicester, LE1 7RH, UK
E-mail : nmw@ion.le.ac.uk
Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555