(^392) | Event-Driven Input and Output
What’s left to be done? Oh yes! We need to add statements to instantiate a ButtonHandler
object and then register it with the button. We can do this locally within main.
ButtonHandler incrementListener;
incrementListener = new ButtonHandler();
incrementButton.addActionListener(incrementListener);
There’s one more detail that we’ve forgotten. The event-handling classes, such as
ActionListener, are in another package,java.awt.event.*, so we also need to import this pack-
age. Everything is now ready to be assembled into a working application.
//**
// SimpleButton application
// This class displays a number and a button, and each time the
// button is clicked, the number is incremented
//**
importjava.awt.; // Supplies layout manager
importjava.awt.event.; // Supplies event classes and interfaces
importjavax.swing.*; // Supplies JFrame class for output display
public classSimpleButton
{
// Field declarations
private static intnumber;
private static JLabel numberLabel;
private staticJButton incrementButton;
// Start of ButtonHandler class
private static classButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)// Event handler method
{
number++;
numberLabel.setText("" + number);
}
}
// End of ButtonHandler class
// Start of main
public static voidmain(String[] args)
{
JFrame outputFrame; // Declare JFrame variable
Container outputPane; // Declare Container variable
ButtonHandler incrementListener; // Declare event listener
// Create a JFrame object
outputFrame = new JFrame();
// Ask the JFrame for its content pane
outputPane = outputFrame.getContentPane();
// Specify the window-closing action
やまだぃちぅ
(やまだぃちぅ)
#1