问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/24978799/main-purpose-of-swingutilities-invokelater