SwingUtilities.invokeLater [英] SwingUtilities.invokeLater

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

问题描述

我的问题与 SwingUtilities.invokeLater 有关.我应该什么时候使用它?每次需要更新 GUI 组件时都必须使用吗?它究竟有什么作用?是否有替代它的方法,因为它听起来不直观并且添加了看似不必要的代码?

My question is related to SwingUtilities.invokeLater. When should I use it? Do I have to use each time I need to update the GUI components? What does it exactly do? Is there an alternative to it since it doesn't sound intuitive and adds seemingly unnecessary code?

推荐答案

每次需要更新 GUI 组件时都必须使用吗?

不,如果您已经在事件调度线程 (EDT) 上,则不会,这在响应用户发起的事件(例如点击和选择)时总是如此.(actionPerformed 方法等,总是由 EDT 调用.)

No, not if you're already on the event dispatch thread (EDT) which is always the case when responding to user initiated events such as clicks and selections. (The actionPerformed methods etc, are always called by the EDT.)

如果您不是使用 EDT 并且想要进行 GUI 更新(如果您想从某个计时器线程或某个网络线程等更新 GUI),您将拥有安排 EDT 执行的更新.这就是这个方法的用途.

If you're not on the EDT however and want to do GUI updates (if you want to update the GUI from some timer thread, or from some network thread etc), you'll have to schedule the update to be performed by the EDT. That's what this method is for.

Swing 基本上是线程不安全的.即,与该 API 的所有交互都需要在单个线程(EDT)上执行.如果您需要从另一个线程(计时器线程、网络线程...)进行 GUI 更新,您需要使用您提到的方法(SwingUtilities.invokeLater、SwingUtilities.invokeAndWait、...).

Swing is basically thread unsafe. I.e., all interaction with that API needs to be performed on a single thread (the EDT). If you need to do GUI updates from another thread (timer thread, networking thread, ...) you need to use methods such as the one you mentioned (SwingUtilities.invokeLater, SwingUtilities.invokeAndWait, ...).

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

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