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

查看:21
本文介绍了我们应该使用 EventQueue.invokeLater 来更新 Java 桌面应用程序中的任何 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.

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

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