Jack Straub
Jack Straub

Reputation: 470

Swing Dialog Layout: run method or constructor?

When I initiate my Swing dialog layout does it make a difference whether I do it in the class's run method:


    public void run()
    {
        frame = new JFrame();
        ...
        frame.setVisible( true );
    }

or the class constructor?


    public MyClass
    {
        frame = new JFrame();
        ...
        frame.setVisible( true );
    }
    public void run()
    {
    }

Thanks

Upvotes: 2

Views: 499

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347334

This is contextual. As @hovercraftfullofeels points out, you need to make sure ALL your UI code is executed in the EDT, including initalisation.

If you're already running in the EDT, then there shouldn't be any need to use InvokeLater (unless you really want to), otherwise you MUST resync the call back to the EDT.

Best to check with EventQueue.isDispatchingThread

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

Yes it does matter, and the reason is that you should call most Swing code, including creation of your JFrame, on the Swing event thread (the Event Dispatch Thread or EDT). To do this, you usually create your Swing GUI in a Runnable, and queue the Runnable on the event thread by calling something like:

SwingUtilities.invokeLater(new Runnable(){
  public void run() {
     // create your Swing GUI here
     frame = new JFrame();
     ...
     frame.setVisible( true );
  }
});

The exceptions are Swing method calls that are documented in the API to be thread-safe such as the repaint() method of Components.

Upvotes: 5

Related Questions