Java Reference
In-Depth Information
figure B.9
Code to handle the
draw button push for
Figure B.1
1 // Handle the draw button push
2 public void actionPerformed( ActionEvent evt )
3 {
4 try
5 {
6 theCanvas.setParams(
7 (String) theShape.getSelectedItem( ),
8 (String) theColor.getSelectedValue( ),
9 Integer.parseInt( theXCoor.getText( ) ),
10 Integer.parseInt( theYCoor.getText( ) ),
11 smallPic.isSelected( ) ? 0 :
12 mediumPic.isSelected( ) ? 1 : 2,
13 theFillBox.isSelected( ) );
14
15 theMessage.setText( "" );
16 }
17 catch( NumberFormatException e )
18 { theMessage.setText( "Incomplete input" ); }
19 }
An important event that needs to be processed is the window-closing
event. This event is generated when an application is closed by pressing on
the that is at the top right-hand corner of the application window. Unfortu-
nately, by default, this event is ignored, so if an event handler is not provided,
the normal mechanism for closing an application will not work.
Window closing is one of several events that is associated with a
WindowListener interface. Because implementing the interface requires us to pro-
vide implementations for many methods (which are likely to be empty bodies),
the most reasonable course of action is to define a class that extends JFrame and
implements the WindowListener interface. This class, CloseableFrame , is shown in
Figure B.10. The window-closing event handler is simple to write—it just calls
System.exit . The other methods remain without a special implementation. The
constructor registers that it is willing to accept the window-closing event. Now
we can use CloseableFrame instead of JFrame throughout.
Notice that the code for CloseableFrame is cumbersome; we will revisit it
shortly and see a use for anonymous inner classes.
Figure B.11 provides a main that can be used to start the application in
Figure B.1. We place this in a separate class, which we call BasicGUI . BasicGUI
extends the class CloseableFrame . main simply creates a JFrame into which we
place a GUI object. We then add an unnamed GUI object into the JFram e's con-
tent pane and pack the JFrame . The pack method simply makes the JFrame as
tight as possible, given its constituent components. The show method displays
the JFrame .
A window-closing
event is generated
when an applica-
tion is closed.
The window-
closing event is
handled by imple-
menting the
WindowListener
i nterface.
CloseableFrame
e xtends JFrame
and implements
WindowListener.
The pack method
simply makes the
JFrame as tight as
possible, given its
constituent compo-
nents. The show
method displays
the JFrame .
 
Search WWH ::




Custom Search