26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 9 Object-Oriented <strong>Program</strong>ming 511<br />

Fig. Fig. 9.34 9.34 Demonstrating anonymous inner classes (part 4 of 4).<br />

Each of the three JTextFields that generate events in this program has a similar anonymous<br />

inner class <strong>to</strong> handle its events, so we discuss only the anonymous inner class for<br />

hourField here. Lines 33–48 are a call <strong>to</strong> hourField’s addActionListener<br />

method. The argument <strong>to</strong> this method must be an object that is an ActionListener (i.e.,<br />

any object of a class that implements ActionListener). Lines 36–46 use special <strong>Java</strong><br />

syntax <strong>to</strong> define an anonymous inner class and create one object of that class that is passed as<br />

the argument <strong>to</strong> addActionListener. Line 36 uses opera<strong>to</strong>r new <strong>to</strong> create an object. The<br />

syntax ActionListener() begins the definition of an anonymous inner class that implements<br />

interface ActionListener. This is similar <strong>to</strong> beginning a class definition with<br />

public class MyHandler implements ActionListener {<br />

The parentheses after ActionListener indicate a call <strong>to</strong> the default construc<strong>to</strong>r of the<br />

anonymous inner class.<br />

The opening left brace ({) at the end of line 36 and the closing right brace (}) at line<br />

46 define the body of the class. Lines 38–44 define the actionPerformed method that<br />

is required in any class that implements ActionListener. Method actionPerformed<br />

is called when the user presses Enter while typing in hourField.<br />

Software Engineering Observation 9.34<br />

When an anonymous inner class implements an interface, the class must define every method<br />

in the interface. 9.34<br />

Method main creates one instance of class TimeTestWindow (line 115), sizes the<br />

window (line 133) and displays the window (line 134).<br />

Windows generate a variety of events that are discussed in Chapter 13. For this<br />

example we discuss the one event generated when the user clicks the window’s close box—<br />

a window closing event. Lines 118–131 enable the user <strong>to</strong> terminate the application by<br />

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!