处理事件调度线程
我有一个关于“事件调度线程”的问题。我有一个 Main 类,它也是一个 JFrame。它初始化代码中的其余组件,其中一些不涉及 Swing,而另一些则涉及。像这样使用 EDT 简单地初始化 Main 类就足够了吗?...
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}
});
}
这样一切都将在事件调度程序线程上运行。
I have a question about the 'Event Dispatch Thread'. I have a Main class that is also a JFrame. It initialises the rest of the components in the code, some of them do not involve Swing and some of them do. Is it enough to simply initialise the Main class using the EDT like this?...
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}
});
}
This way everything would run on the Event Dispatcher thread.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这通常是足够的,直到您开始使用后台线程进行计算、数据采集等。然后您需要在更改 swing 组件或其模型之前开始小心地验证您是否处于 EDT 上。
您可以使用以下方法测试是否在 EDT 上执行:
另外,请参阅 SwingWorker 类,了解如何将工作移交给后台线程并在 EDT 上处理结果的详细信息
That is generally sufficient until you start making use of background threads for calculations, data acquisition, etc. Then you need to start being careful to verify that you are on the EDT prior to altering a swing component or its model.
You can test whether you're executing on the EDT with:
Also, see the SwingWorker class for details on how to hand off work to a background thread and process results on the EDT
这是要走的路。您唯一应该注意的是,您向 Swing 组件注册的侦听器是否会生成一个新线程(通常用于执行一些长时间计算)。如果此类新线程要执行 GUI 操作,则需要使用
invokeLater
。This is the way to go. The only thing you should be careful about is if a listener that you register with the Swing components will spawn a new Thread (often for carrying out some long computation). Such new threads will need to use
invokeLater
if they are to carry out GUI operations.这就是 Sun 教程中所有示例的工作方式。阅读 Swing 教程中关于并发的部分有关为什么这样做的更多信息。
That is the way all the examples from the Sun tutorial work. Read the section from the Swing tutorial on Concurrency for more information on why it is done this way.
Devon_C_Miller的答案是正确的。我只是想指出调用事件调度线程的快捷方式。
以下是我启动所有 Swing 应用程序的方法。
您可以将其复制到每个 Swing 项目,只需更改名称即可。
Devon_C_Miller's answer is correct. I just want to point out a shortcut to invoking the event dispatch thread.
Here's how I start all of my Swing applications.
You can copy this to every Swing project, just by changing the names.