Java Reference
In-Depth Information
Runnable runnable = new Runnable() {
public void run() {
// Do work to be done
}
}
EventQueue.invokeLater(runnable);
If you want your Swing GUI creation to be thread-safe, you should follow this pattern with
all of your Swing code. If you need to access the command-line arguments, just add the final
keyword to the argument declaration: public static void main(final String args[]) . This
may seem like overkill for a simple example like this, but it does ensure the thread safety of your
program, making sure that all Swing component access is done from the event-dispatch thread.
(However, calls to repaint() , revalidate() , and invalidate() don't need to be done from the
event-dispatch thread.)
Note In addition to the invokeLater() and invokeAndWait() methods of the EventQueue class, there
are wrapper methods of the same name in the SwingUtilities class. Since the SwingUtilities calls just
redirect the calls on to the EventQueue class, you should avoid the extra layer of indirection and access
EventQueue directly. These wrapper methods were created for an early Swing version, prior to the existence
of the EventQueue class.
One additional line from Listing 2-1 requires some extra explanation:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
By default, if you click the little X in the title bar of the window shown in Figure 2-3, the
application does not close; instead, the frame is made invisible. Setting the default close oper-
ation to JFrame.EXIT_ON_CLOSE , as in Listing 2-1, causes the application to exit if the user clicks
the X. You'll learn more about this behavior in Chapter 8, which explores the JFrame class.
Using SwingUtilities for Mouse Button Identification
The Swing component set includes a utility class called SwingUtilities that provides a collection
of generic helper methods. You will look at this class periodically throughout this topic when a
particular set of methods for this class seems useful. For the button example in Listing 2-1, the
methods of interest are related to determining which mouse button has been selected.
The MouseInputListener interface consists of seven methods: mouseClicked(MouseEvent) ,
mouseEntered(MouseEvent) , mouseExited(MouseEvent) , mousePressed(MouseEvent) , and
mouseReleased(MouseEvent) from MouseListener ; and mouseDragged(MouseEvent) and
mouseMoved(MouseEvent) from MouseMotionListener . If you need to determine which buttons
on the mouse were selected (or released) when the event happened, check the modifiers prop-
erty of MouseEvent and compare it to various mask-setting constants of the InputEvent class.
For instance, to check if a middle mouse button is pressed for a mouse press event, you
could use the following code in your mouse listener's mousePressed() method:
 
Search WWH ::




Custom Search