Java Reference
In-Depth Information
Action Handling: Making Buttons Work
Problem
Your button doesn't do anything when the user presses it.
Solution
Add an
ActionListener
to do the work.
Discussion
Event listeners come in about half a dozen different types. The most common is the
Ac-
tionListener
, used by push buttons, text fields, and certain other components to indicate
that the user has performed a high-level action, such as activating a push button or pressing
ject, register it with the event source (such as the push button), and wait. Later, when and if
the user pushes the button, the button will call your
Listener
.
Figure 14-3. AWT listener relationships
Here's some simple code in which pushing a button causes the program to print a friendly
message:
/** Demonstrate simple use of Button */
public
public class
class
ButtonDemo
ButtonDemo
extends
extends
JFrame
implements
implements
ActionListener
{
JButton
b1
;
public
public
ButtonDemo
() {
setLayout
(
new
new
FlowLayout
());
add
(
b1
=
new
new
JButton
(
"A button"
));