Java Reference
In-Depth Information
The
JButton
Class
An object of the class
JButton
is displayed in a GUI as a component that looks like a
button. Click the button with your mouse to simulate pushing it. When creating an object
of the class
JButton
using
new
, you can give a string argument to the constructor and the
string will be displayed on the button.
You can add a
JButton
object to a
JFrame
by using the method
add
with the
JFrame
as
the calling object and the
JButton
object as the argument. You will later see that you can
also add buttons to other GUI objects (known as “containers”) in a similar way.
A button's action is programmed by registering a listener with the button using the method
addActionListener
.
EXAMPLE
JButton niceButton =
new
JButton("Click here");
niceButton.addActionListener(
new
SomeActionListenerClass());
someJFrame.add(niceButton);
The Close-Window Button Is Not in the Class
JButton
The buttons that you add to a GUI are all objects of the class
JButton
. The close-window
button and the other two accompanying buttons on a
JFrame
are not objects of the class
JButton
. They are part of the
JFrame
object.
Action Listeners and Action Events
Clicking a button with your mouse (or activating certain other items in a GUI) creates
an object known as an event and sends the event object to another object (or objects)
known as the listener(s). This is called
firing the event
. The listener then performs
some action. When we say that the event is “sent” to the listener object, what we really
mean is that some method in the listener object is invoked with the event object as the
argument. This invocation happens automatically. Your Swing GUI class definition
will not normally contain an invocation of this method. However, your Swing GUI
class definition does need to do two things:
• First, for each button, it needs to specify what objects are listeners that will respond
to events fired by that button; this is called
registering
the listener.
• Second, it must define the methods that will be invoked when the event is sent to
the listener. Note that these methods will be defined by you, but in normal circum-
stances, you will never write an invocation of these methods. The invocations will
take place automatically.
The following lines from Display 17.2 create an
EndingListener
object named
buttonEar
and register
buttonEar
as a listener to receive events from the button
named
endButton
:
EndingListener buttonEar =
new
EndingListener( );
endButton.addActionListener(buttonEar);
registering a
listener
addAction
Listener