Java Reference
In-Depth Information
We have already discussed adding components, such as buttons, to a JFrame .
The button is added to the JFrame by the following line from Display 17.2:
adding a
button
firstWindow.add(endButton);
In the next subsection we explain the lines from Display 17.2 involving the method
addActionListener .
The JButton Class
An object of the class JButton is displayed in a GUI as a component that looks like a button.
You 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.
registering a
listener
Search WWH ::




Custom Search