Main purpose of SwingUtilities invokeLater

ぐ巨炮叔叔 提交于 2019-12-29 01:32:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!