Java Swing Multiple Event Listeners for a Single Event Source in a single-threaded environment
I am currently learning Swing, and I am new to GUI development in general. In my test application, I have multiple e开发者_C百科vent listners for a single event source, and I am wondering which one of these event listeners will be excecuted first.
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.
Lastly, I would like to know some common cases where I have to use multiple threads in Swing.
Thanks!
I will try to answer all 3 of your questions. First of all, the order that the ActionListener
s 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
.
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.
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.
The Oracle network has a great tutorial on concurrency in Swing. I recommend you check it out.
A Swing programmer deals with the following kinds of threads:
- Initial threads, the threads that execute initial application code.
- The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
- Worker threads, also known as background threads, where time-consuming background tasks are executed.
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
.
精彩评论