(^390) | Event-Driven Input and Output
3.Register the listener by calling the addActionListenermethod associated with the
button, and passing it the variable of the listener class.
An Event-Handling Example
We have seen how to create labels and buttons, how to name a button event, and how to reg-
ister its listener. We now have all of the syntax that we need to write an application with a
user interface dialog that responds to events. But what goes in the body of the event handler?
We’ve been discussing the creation and handling of events in the abstract. In solving a real
problem, we would know beforehand what a button in our interface should do. Then it would
be clear what must happen in the handler.
Let’s look at a very simple problem to illustrate how it all works. We will pick something
absolutely trivial so that we can focus on the essential structure and not on how to solve the
underlying problem. Suppose we want a user interface that contains a label and a button.
The label begins with the number 0 in it, and each time we click the button, the number is
incremented. That is, in the button handler, we add 1 to the current value of number and re-
display it in the label.
number++;
numberLabel.setText("" + number);
We used the setTextmethod in a previous example without mentioning it. This instance
method of a JLabelobject simply replaces the text in a label with the new string that is its
argument. (Clearly,setTextis a transformer and thus JLabelobjects are mutable.)
Now, let’s look at the code for setting up a typical frame, since we’re already familiar with
how to do this.
//******************************************************************
// 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
importjavax.swing.*; // Supplies JFrame class for output display
public classSimpleButton
{
public static voidmain(String[] args)
{
JFrame outputFrame; // Declare JFrame variable
Container outputPane; // Declare Container variable
// Create a JFrame object
outputFrame = new JFrame();
// Ask the JFrame object to return a content pane Container object
outputPane = outputFrame.getContentPane();
// Specify the action to take when the window is closed
outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
T
E
A
M
F
L
Y
Team-Fly®