Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

java - Main purpose of SwingUtilities invokeLater

I have this code snippet

import javax.swing.SwingUtilities;

public class Client1 {

    public static void main( String[] args ) {

        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                //new MyWindow( "Bayog" );
                new MyWindowV2( "Bayog" );
            }
        } );   
    }
}

what is the difference if i will not use SwingUtilities?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Suppose the code within the run method modifies a UI element. If you try to execute that code from a non-UI thread, it will fail: all UI operations must be performed in the UI thread (aka the event dispatch thread).

SwingUtilities.invokeLater allows you to say "run this bit of code, but do so in the UI thread". As such, it's great for background threads that still want to update the UI. Another option is to use SwingWorker, but that's not always appropriate as it requires that the code that "knows" it needs to use the UI thread is the code that sets up the background thread.

See the Swing Threading Tutorial for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...