线程和Swing

来源:互联网 发布:汉语网络域名注册 编辑:程序博客网 时间:2024/05/23 13:29
 基于效率和用户可扩展性的考虑,swing被设计成非线程安全的。swing程序中有两个线程被先后创建main主线程事件分派线程,main可能很快就退出了,swing事件响应代码在事件分派线程中执行。

    若需要完成一个耗时的任务,则可以启动一个新线程来处理。但是不能在新线程中直接操作swing组件!这可能导致swing崩溃。一种情况就是我们需要在更新界面的进度条或标签等。处理的办法是使用java.awt.EventQueue,将更新界面的代码放入static的invokeLater或invokeAndWait方法中。如更新一个标签[1]

    EventQueue.invokeLater(new Runnable(){          public void run(){                lable.setText(percentage + "% complete");          }     }); 

这样就将事件发布到事件队列中。没有新的线程被创建!

invokeLater方法直接返回,run()被异步执行。

invokeAndWait则直到run()执行结束返回



You only need to use invokeLater when you want to update your UI from another thread that is not the UI thread (event dispatch thread).

Suppose you have a handler for a button-click and you want to change the text of a label when someone clicks the button. Then it's perfectly save to set the label text directly. This is possible because the handler for the button-click event runs in the UI thread.

Suppose, however, that on another button-click you start another thread that does some work and after this work is finished, you want to update the UI. Then you useinvokeLater. This method ensures that your UI update is executed on the UI thread.

So in a lot of cases, you do not need invokeLater, you can simply do UI updates directly. If you're not sure, you can useisDispatchThread to check whether your current code is running inside the event dispatch thread.


0 0
原创粉丝点击