1

What will happen if we are creating the Java Swing application in main thread? Rule of thumb is that we have to start the application in EDT??please help.

3 Answers3

2

Q1. Rule of thumb is that we have to start the application in EDT

Not really a rule of thumb - more like a requirement specified by the library:

In general Swing is not thread safe. All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.

Q2. What will happen if we are creating the Java Swing application in main thread?

It might work or not: the behaviour is unspecified. An example is given on that same page:

If you modify the model on a separate thread you run the risk of exceptions and possible display corruption.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • It might work if there are no exceptions? –  Nov 15 '12 at 17:30
  • *"and possible display corruption"* and possibly other issues like a component not updating properly or events not being fired etc, etc. – assylias Nov 15 '12 at 17:31
1

What will happen if we are creating the Java Swing application in main thread? Rule of thumb is that we have to start the application in EDT??

  • theoratically doesn't matter, important is to avoiding to create GUI in non_static classes or void, in compare with Objects created in main class

  • Object created in main class isn't directly accesible, same issue with extends JComponents

  • important is to create and showing Swing GUI in Initial Thread

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 2
    "I always invoke my methods on the EDT so I don't waste time chasing gremlins."—[camickr](http://stackoverflow.com/a/4858895/230513) – trashgod Nov 15 '12 at 19:12
1

assylias and mKorbel have great answers.

I start every Swing application with a variation of the following class:

import javax.swing.SwingUtilities;

import com.ggl.stopwatch.view.StopwatchFrame;

public class Stopwatch implements Runnable {

    @Override
    public void run() {
        new StopwatchFrame();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Stopwatch());
    }

}
Community
  • 1
  • 1
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111