Java Reference
In-Depth Information
8 JOptionPane.showMessageDialog(
null
,
9 "You clicked the button!");
10 }
11 }
Now that we've written this class, we can attach a
MessageListener
object to
any button or other component of interest, and it will respond to action events on that
component. For example, if we attach a
MessageListener
to a button, an option
pane will pop up whenever that button is clicked. To attach the listener, we'll use a
method called
addActionListener
that is found in several Swing components and
that accepts a parameter of type
ActionListener
.
For example, we can add the following line to the
ComponentsExample
program
we developed earlier to attach the listener to the first button:
// attach a listener to handle events on this button
button1.addActionListener(new MessageListener());
Here is the result when the program is executed and the user clicks on the button:
Note that a listener only responds to events on components to which it is added. If
the user clicks the “Click me!” button, nothing will happen. If we want the same event
to occur when the user clicks this button, we must add a
MessageListener
to it. If
we want a different response to occur on a click of this button, we can write a second
class that implements
ActionListener
and attach one of its objects to the button.
To summarize, follow these steps to handle an event in Java:
•
Write a class that implements
ActionListener
.
•
Place the code to handle the event into its
actionPerformed
method.
•
Attach an object of your listener class to the component of interest using its
addActionListener
method.
Earlier, we used a
FlowLayout
to position the components in our frame. In this sec-
tion, we will explore several different layout manager objects that can be used to
position components in a variety of ways.
Search WWH ::
Custom Search