Java Reference
In-Depth Information
Laying out the JFrame
In the class, two buttons are created, eastButton and westButton . The
assertion for the two declarations, the class invariant , lets the reader know that
exactly one of the buttons is enabled at any point. As might be expected, the con-
structor adds the two buttons to the content pane. And, two statements disable the
west button and enable the east button, thus truthifying the class invariant. At the
end of the constructor, the frame is packed, as usual.
Making the buttons listen
Making a button listen is a three-step process:
1. Write a procedure actionPerformed to process a button click. It must
have one argument of type ActionEvent . Our procedure is given at the
bottom of the class in Fig. 17.14. It stores in local variable b a boolean
that indicates whether button eastButton is enabled and sets the en-
abledness of the two buttons accordingly. Here, you see calls to two
methods of class JButton : isEnabled and setEnabled . This particular
procedure does not access its parameter e . We talk about that later.
2. Have the class implement interface ActionListener . This ensures that
actionPerformed appears in the class. Do this by putting an implements
clause in the method header, as shown in Fig. 17.14. Do not worry if you
do not know about interfaces and implements clauses. Just do this.
3. Add an instance of this class as an action listener for the button. For
example, the following call adds this instance as a listener of button
westButton . Remember that keyword this , used in a method, refers to
the instance in which the method appears.
westButton.addActionListener( this );
Figure 17.15:
Listening to mouse events
Search WWH ::

Custom Search