Java Reference
In-Depth Information
LISTING 4.11
continued
//-----------------------------------------------------------------
// Constructor: Sets up the GUI.
//-----------------------------------------------------------------
public
PushCounterPanel ()
{
count = 0;
push =
new
JButton ("Push Me!");
push.addActionListener (new ButtonListener());
label =
new
JLabel ("Pushes: " + count);
add (push);
add (label);
setPreferredSize (
new
Dimension(300, 40));
setBackground (Color.cyan);
}
//*****************************************************************
// Represents a listener for button push (action) events.
//*****************************************************************
private class
ButtonListener
implements
ActionListener
{
//--------------------------------------------------------------
// Updates the counter and label when the button is pushed.
//--------------------------------------------------------------
public void
actionPerformed (ActionEvent event)
{
count++;
label.setText("Pushes: " + count);
}
}
}
The
PushCounterPanel
constructor sets up the GUI. The call to the
JButton
constructor takes a
String
parameter that specifies the text shown on the button.
The button and the label are added to the panel.
The only event of interest in this program occurs when the button is pushed. To
respond to the event, we must create a listener object for that event, so we must
write a class that represents the listener.
Search WWH ::
Custom Search