5. Explain the Swing event dispatcher mechanism

Swing components can be accessed by the Swing event dispatching thread. A few operations are guaranteed to be thread-safe but most are not. Generally the Swing components should be accessed through this event dispatching thread. The event-dispatching thread is a thread that executes drawing of components and eventhandling code. For example the paint() and actionPerformed() methods are automatically executed in the eventdispatching thread. Another way to execute code in the event-dispatching thread from outside event-handling or drawing code, is using SwingUtilities invokeLater() or invokeAndWait() method. Swing lengthy initialization tasks (e.g. I/O bound and computationally expensive tasks), should not occur in the event-dispatching thread because this will hold up the dispatcher thread. If you need to create a new thread for example, to handle a job that’s computationally expensive or I/O bound then you can use the thread utility classes such as SwingWorker or Timer without locking up the event-dispatching thread.

SwingWorker – creates a background thread to execute time consuming operations.

Timer – creates a thread that executes at certain intervals.

However after the lengthy initialization the GUI update should occur in the event dispatching thread, for thread safety reasons. We can use invokeLater() to execute the GUI update in the event-dispatching thread. The other scenario where invokeLater() will be useful is that the GUI must be updated as a result of non-AWT event.


No comments:

Post a Comment