单个线程环境中单个事件源的Java Swing多事件侦听器 [英] Java Swing Multiple Event Listeners for a Single Event Source in a single-threaded environment

查看:188
本文介绍了单个线程环境中单个事件源的Java Swing多事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习Swing,而且我是GUI开发的新手。在我的测试应用程序中,我有一个单个事件源的多个事件列表器,我想知道这些事件监听器中的哪一个将首先被激活。

I am currently learning Swing, and I am new to GUI development in general. In my test application, I have multiple event listners for a single event source, and I am wondering which one of these event listeners will be excecuted first.

此外,我是很想知道Swing事件处理在单线程环境中是如何工作的,特别是当你有一个单个事件源的多个监听器时。

Also, I am curious to know how Swing event-handling works in a single-threaded environment, especially when you have multiple listeners for a single event source.

最后,我想知道我必须在Swing中使用多个线程的一些常见情况。

Lastly, I would like to know some common cases where I have to use multiple threads in Swing.

谢谢!

推荐答案

我会尝试回答你的所有3个问题。首先,未指定 ActionListener s fire的顺序。人们永远不应该假设他们会发射一个特定的命令。如果您需要按特定顺序执行操作,请将它们放在相同的 ActionListener 中。

I will try to answer all 3 of your questions. First of all, the order that the ActionListeners fire is not specified. One should never assume a specific order that they will fire. If you need actions to take place in a specific order, put them in the same ActionListener.

编程Swing时,你将几乎始终处于多线程环境中。有一个称为事件调度线程(EDT)的线程。这是处理所有事件的线程。你要做的任何其他处理应该在不同的线程上完成,否则你的Swing GUI会变得没有响应。

When programming Swing, you will 'almost' always be in a multi-threaded environment. There is one thread called the Event Dispatch Thread (EDT). This is the thread that handles all events. Any other processing you do should be done on a different thread, otherwise your Swing GUI can become unresponsive.

Swing中多个线程的常见情况是你需要的任何时候做一些需要花费很长时间的处理。 (激烈的计算,IO,数据库连接)您将希望在与EDT不同的线程上进行艰苦的工作。这将使您的GUI保持响应。

A common case for multiple threads in Swing is any time you need to do some processing that takes an extended amount of time. (Intense calculations, IO, database connections) You will want to do the hard work on a separate thread from the EDT. That will keep your GUI responsive.

Oracle网络有一个很好的Swing并发教程。我建议您查看

The Oracle network has a great tutorial on concurrency in Swing. I recommend you check it out.


Swing程序员处理以下类型的线程:

A Swing programmer deals with the following kinds of threads:


  • 初始线程,执行初始应用程序代码的线程。

  • 事件调度线程,执行所有事件处理代码。大多数与Swing框架交互的代码也必须在此线程上执行。

  • 工作线程,也称为后台线程,执行耗时的后台任务。

Swing中任何多线程问题的规范答案是使用 SwingWorker 。它允许您使用EDT在单独的线程上轻松协调后台工作。像往常一样,Oracle有一个关于如何使用 SwingWorker

The canonical answer to any multi-threading questions in Swing is to use a SwingWorker. It allows you to easily coordinate background work on a separate thread with the EDT. As usual, Oracle has a great tutorial on how to use SwingWorker.

这篇关于单个线程环境中单个事件源的Java Swing多事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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