Java Reference
In-Depth Information
Button events
To the left in Fig. 17.13 is a JFrame with two buttons. The east button is enabled,
so pressing it will cause an action to be performed; the west button is disabled
and appears grayed out. Clicking the east button disables it and enables the west
button, changing the JFrame into the state shown to the right in Fig. 17.13. Then,
clicking the west button disables it and enables the east button again.
The JFrame in Fig. 17.13 is an instance of class ButtonDemo1 of Fig. 17.14.
We show you how this class accomplishes its task in two steps. First, we show
the part that lays out the JFrame ; second, we show how to make the buttons lis-
ten to mouse clicks. Note that the class contains a statement to import classes of
package java.awt.event ; some of these classes are used in listening to events.
Obtain the
class of Fig.
17.13 from les-
son page 17-4.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo1 extends JFrame implements ActionListener {
// Class invariant: exactly one of eastButton and westButton is enabled
private JButton westButton= new JButton("west");
private JButton eastButton= new JButton("east");
/** Constructor: invisible frame with title t and 2 buttons */
public ButtonDemo1(String t) {
super (t);
Container cp= getContentPane();
cp.add(westButton, BorderLayout.WEST);
cp.add(eastButton, BorderLayout.EAST);
westButton.setEnabled( false );
eastButton.setEnabled( true );
westButton.addActionListener( this );
eastButton.addActionListener( this );
/** Process a click of a button */
public void actionPerformed(ActionEvent e) {
boolean b= eastButton.isEnabled();
Figure 17.14:
Listening to buttons
Search WWH ::

Custom Search