Search |
||
The Single Thread Rule in SwingPosted by cayhorstmann on June 11, 2007 at 9:44 PM PDT
The Single Thread Rule in Swing
The original rule is well explained in this classic article. It is:
“Realized” is defined in that article, and it is a bit intricate. But for the most part, it means that you should stop messing with Swing components in the main thread after calling pack (!) or setVisible(true), whichever comes first.
public class BadExample
{
public static void main(String... args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(300, 300); // BAD
}
}
But the latest Javadoc goes quite a bit further. It says “All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.”
public class StillBad
{
public static void main(String... args)
{
JFrame frame = new JFrame(); // BAD
frame.setSize(300, 300); // BAD
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // BAD
frame.setVisible(true); // BAD
}
}
The Javadoc then goes on: “The preferred way to transfer control and begin working with Swing is to use invokeLater.”
public class PureGoodness
{
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Ugh. That won't win the hearts and minds of my students. I suppose I could rewrite it as public class PureGoodness implements Runnable
{
public void run()
{
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String... args)
{
EventQueue.invokeLater(new PureGoodness());
}
}
Still ugh. I am left with some questions and I fervently hope that some of you have answers:
»
Comments
Comments are listed in date ascending order (oldest first)
|
||
|
|