Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to start a swing application

What is the best practice way to start a java swing application? Maybe there is another way to do it.

I want to know if i have to use the SwingUtilities class to start the application (secound possibility) or not (first possibility).

public class MyFrame extends JFrame {

public void createAndShowGUI() {
    this.setSize(300, 300);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    // add components and stuff
    this.setVisible(true);
}

public static void main(String[] args) {

    // First possibility
    MyFrame mf = new MyFrame();
    mf.createAndShowGUI();

    // Secound possibility
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            MyFrame mf = new MyFrame();
            mf.createAndShowGUI();
        }
    });
}

}

like image 692
Charmin Avatar asked Sep 24 '13 08:09

Charmin


People also ask

Which is better JavaFX or Swing?

From a Java developer perspective, both technologies are highly useful in writing pluggable UI components. With its vast UI component library, Swing can provide added advantage to the developer, whereas when it comes to design modern and rich internet application, JavaFX can supersede Swing.

What are Swing applications?

The Swing Application Framework (JSR 296) is a Java specification for a simple application framework for Swing applications, with a graphical user interface (GUI) in computer software. It defines infrastructure common to most desktop applications, making Swing applications easier to create.


1 Answers

Only the second way is correct. Swing components must be created and accessed only in the event dispatch thread. See concurrency in swing. The relevant quote:

Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must run on the event dispatch thread. This restriction is discussed further in the next section.

So yes, you need to use invokeLater().

like image 165
kiheru Avatar answered Oct 04 '22 03:10

kiheru