Martynas Žukovas
Martynas Žukovas

Reputation: 149

Swing GUI one simple thing

I have one simple question why do I need write code like this with

SwingUtilities.invokeLater(new Runnable(){

If programm create same frame without it?

code with SwingUtilities

import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class App {
    public static void main (String args[]){    
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JFrame frame = new JFrame("Hello world swing"); 
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(300, 400);        
            }
        });
    }
}

code without swing utilities.

import javax.swing.JFrame;

public class App {
    public static void main (String args[]){    
        JFrame frame = new JFrame("Hello world swing");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 400);
    }
}

Upvotes: 3

Views: 148

Answers (1)

veritas
veritas

Reputation: 2444

Swing is not thread-safe, and is single-threaded. It relies on the Event Dispatch Thread (EDT) for creating, updating and rendering its components.

See http://en.wikipedia.org/wiki/Event_dispatching_thread

SwingUtilities.invokeLater and SwingUtilities.invokeAndWait are utility methods to basically put your Swing related task into the EDT.

If you don't do it, it may fail eventually. You will see weird results, as your application becomes bigger.

Always do GUI (SWING) related operations on EDT.

Also most GUIs are single-threaded. So is Swing. Therefore, trying to access Swing from more than one thread will increase the risk of application failing. Read this http://codeidol.com/java/java-concurrency/GUI-Applications/Why-are-GUIs-Single-threaded/

In your code, a Swing Operation (creation of JFrame) is being done on main thread, which is not recommended. Use SwingUtilities.invokeLater().

Upvotes: 4

Related Questions