Sams Teach Yourself C in 21 Days

(singke) #1
More Java Techniques 755

BD6


Next, the layout manager object is associated with the container object using the
setLayoutmethod, typically in the constructor:
setLayout(lm);
You’ll see how this is done in detail in the next demonstration program.

Handling Events
To deal with user events, such as the user clicking a button or any other component, Java
uses theactionmethod. The syntax for this method is as follows:
public boolean action(Event evt, Object arg) {
}
The first argument is an Eventobject that represents the event that occurred. The second
argument depends on the identity of the component that receives the event, as explained
in Table B6.1.

TABLEB6.1 Action method object arguments for different components
Component Argument type Argument data
Button String The button’s label.
Check box Boolean Always true.
Radio button Boolean Always true.
Choice menu String The label of the selected item.
Text field String The field’s text.

The action method is called every time a related user event occurs. Code in the method
must make use of the arguments to determine what component received the action and
then direct execution appropriately. The method should return trueif code in the method
has handled the event, or falseif the event has not been handled and needs to be passed
up the object hierarchy for handling elsewhere.

Working with Controls and Events
Now that you’ve read a little about controls and events, it is time to look at a demonstra-
tion. The next program uses buttons, a layout manager, pop-up windows, and user events.
The program displays a main window that contains two buttons. Click one of the buttons
to display a second pop-up window, then click the Close button in the pop-up window to
close it. Finally, click the second button in the main window to end the program. Listing
B6.5 is the PopUpWindowclass, and Listing B6.6 presents the main program.

41 448201x-Bonus6 8/13/02 11:23 AM Page 755

Free download pdf