18.3. Avoiding Deadlocks in GUI Code
Preparing the application window and any components it contains and displaying it is described as realizing the window. Calling setVisible() for an application window object realizes the window. As I said in the previous section, once an application GUI has been realized, modifying or querying it on the main thread can cause deadlock because user interactions with the GUI, such as clicking a menu item, are handled in the event-dispatching thread. There is also the rare possibility with some types of Swing components that deadlocks can occur even when it is not apparent that you are modifying the GUI after it has been realized. You can avoid any possibility of deadlock in your application arising from your GUI creation code by arranging to execute all the code that creates the GUI on the event-dispatching thread.
The javax.swing.SwingUtilities class provides the static invokeLater() method, which makes creating the GUI on the event-dispatching thread very easy. The invokeLater() method expects an argument of type Runnable, which is a reference to an object of a type that implements the Runnable interface. A simple way of defining a Runnable object that will create the GUI for an application is to use an anonymous class. Let's see how that works.
Try It Out: Creating the GUI on the Event-Dispatching ThreadYou can modify the last version of the Sketcher application in Chapter 17 to use the invokeLater() method from the SwingUtilities class. ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access