我们是否应该在Java桌面应用程序中使用EventQueue.invokeLater进行任何GUI更新? [英] Should we use EventQueue.invokeLater for any GUI update in a Java desktop application?

查看:105
本文介绍了我们是否应该在Java桌面应用程序中使用EventQueue.invokeLater进行任何GUI更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道通过使用此方法,runnable参数将提交给系统EventQueue。
但是,如果使用此方法完成所有GUI更新吗?我的意思是,如果我想说,更改JButton的文本,我应该使用这样的东西:

I know that by using this method, the runnable parameter is submitted to the system EventQueue. But should all GUI updates be done this using this method? I mean, if i want to say, change a text of JButton, should i use something like this:

java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
         jButton1.setText("changed text");
      }
});

如果我应该使用这种方法,我们可以使用任何模式来避免这种重复的代码?

If i should use this approach, any pattern we can use to avoid this repetitive code?

推荐答案

你只需要使用 invokeLater 当你想要更新你的来自另一个不是UI线程的线程的UI(事件调度线程)。

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).

假设您有一个按钮单击的处理程序,并且您想要更改文本当有人点击按钮时标记。然后直接设置标签文本就完全可以了。这是可能的,因为按钮单击事件的处理程序在UI线程中运行。

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.

但是,假设在另一个按钮上单击,则启动另一个执行某些工作的线程,在完成此工作后,您需要更新UI。然后使用 invokeLater 。此方法可确保在UI线程上执行UI更新。

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 use invokeLater. This method ensures that your UI update is executed on the UI thread.

因此在很多情况下,您不需要 invokeLater ,您可以直接进行UI更新。如果您不确定,可以使用 isDispatchThread 检查当前代码是否在事件派发线程内运行。

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 use isDispatchThread to check whether your current code is running inside the event dispatch thread.

这篇关于我们是否应该在Java桌面应用程序中使用EventQueue.invokeLater进行任何GUI更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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