Skip to main content

Debugging Swing - is it really difficult ?

Posted by alexfromsun on November 23, 2005 at 1:57 AM PST

Every experienced Swing developer knows that Swing components must be accessed from Event Dispatch Thread (EDT) only. Working with JComponents from any other thread may lead to unpredictable result.

Consider the following code:

import javax.swing.*;
import java.awt.*;
public class BadCode { public static void main(String args[]) { createGui(); }
private static void createGui() {
//this code must be run on EventDispatch thread!
JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new GridBagLayout()); JEditorPane pane = new JEditorPane(); pane.setText("Edt matters!"); pane.setSelectionEnd(pane.getText().length()); frame.getContentPane().add(pane); frame.setSize(new Dimension(200, 100)); frame.setVisible(true);
//clear selection pane.setSelectionStart(0); pane.setSelectionEnd(0); } }

Running this code I get the desirable unselected JEdiorPane, ... sometimes

Sometimes I get it like this:

Working with Swing not from EDT, you might see your components and layouts distorted or not reflected the current state.
It can work most of the times, but sometimes not, without any guarantee.

Actually the main rule is
"If you work with Swing not from EDT all sorts of strange things can happen".

It's been so many articles like this and this, so I suppose that most of Swing programmers know how it works and do the right thing.

Our previous example might be fixed this way:

public static void main(String args[]) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {

Pretty easy, right?

The fact that every JComponent's listener is automatically invoked on EDT makes it even more easy.

In my opinion, understanding that Swing is a single-threaded library is not difficult
(but it is not a big deal, since I am a Swing developer).

Funny thing, I took part in interviewing several java programmers who claimed to know Swing well, but at the same time some of them had no idea what EDT is.
One guy said that he'd seen Swing's strange behaviour only once, but he fixed it by changing code lines' order.
(Of course, he worked with Swing from incorrect thread)

That's why I am really interested in your opinion,
please look to this questions and give your valuable suggestions.

Set of questions

  1. Is it a common situation when developers incorrectly use Swing components from another thread and get the strange behaviour I mentioned earlier ?
  2. Is it difficult to make sure that all Swing code is invoked on EDT and find places when it is not ?
  3. Should we invent something to make Swing debugging easier?
  4. Would it be useful if we mark all EDT-only methods with special annotaion ?

Any comments would be appreciated!

I also posted new topic to javadesktop forum


Related Topics >>