SwingUtilities invokeLater的主要目的 [英] Main purpose of SwingUtilities invokeLater

查看:115
本文介绍了SwingUtilities invokeLater的主要目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码

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" );
            }
        } );   
    }
}

如果我不使用SwingUtilities有什么区别?

what is the difference if i will not use SwingUtilities?

推荐答案

假设 run 方法中的代码修改了UI元素。如果您尝试从非UI线程执行该代码,它将失败:所有UI操作必须在UI线程(也称为事件调度线程)中执行。

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 允许您说运行这段代码,但在UI线程中执行此操作。因此,对于仍然想要更新UI的后台线程来说,它非常棒。另一种选择是使用 SwingWorker ,但这并不总是合适的,因为它要求知道它需要使用UI线程的代码是设置后台线程的代码。

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.

有关更多详细信息,请参阅 Swing Threading教程

See the Swing Threading Tutorial for more details.

这篇关于SwingUtilities invokeLater的主要目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆