// Author: David Galles
// Demonstrating simple subclassing of JPanel, and adding (functional!) buttons to Panels
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ButtonPanel2 extends JPanel
{
JButton button;
JLabel label;
int numberOfPresses = 0;
// Constructor
// Sets up a panel with a buttons and a Label. The label tells how many
// times the button has been pressed
public ButtonPanel2()
{
button = new JButton("Press Me!");
add(button);
button.addActionListener(new ButtonListener());
label = new JLabel("Number of Button Preses = " + numberOfPresses);
add(label);
setPreferredSize(new Dimension(250, 100));
}
private class ButtonListener implements ActionListener
{
// method actionPerformed
// INPUT: event: describes the action that was performed (though since this listener
// is only attached to buttons, we know what the event must be -- a
// button press! More complex widgets would require us to examine the
// event more closely
// Implements a button press -- updates the label which tells how many times the button
// was pressed
public void actionPerformed(ActionEvent event)
{
numberOfPresses++;
label.setText("Number of Button Presses = " + numberOfPresses);
}
}
}