Page 696 - Introduction to Programming with Java: A Problem Solving Approach
P. 696
662 Chapter 16 GUI Programming Basics
There are only two syntactic differences between the two code fragments—the addActionListener call and the listener class heading. There are no semantic differences between the two code fragments, so the Greeting program and the GreetingAnonymous program behave the same.
16.12 JButton Component
It’s now time to learn another GUI component—a button component.
User Interface
If you press a button on an electronic device, something usually happens. For example, if you press the power button on a television, the television turns on or off. Likewise, if you press/click a GUI button com- ponent, something usually happens. For example, in Figure 16.1’s TrustyCredit window, if you click the OK button, then the entered credit card numbers get processed by the TrustyCredit company.
Implementation
To create a button component, call the JButton constructor like this: JButton helloButton = new JButton("Press me");
If it’s omitted, the label gets the empty string by default and the button displays with a blank face (no writing or icons on it).
After you have created the helloButton, add it to your window, like this:
add(helloButton);
To make the button useful, you’ll need to implement a listener. As with the text box listeners, button listen- ers must implement the ActionListener interface. The ActionListener interface dictates that you must have an actionPerformed event handler method. The code skeleton looks like this:
private class Listener implements ActionListener
{
}
public void actionPerformed(ActionEvent e)
{
}
<do-something>
Apago PDF Enhancer
We’re using private instead of public for the listener class because a listener normally is implemented as an inner class, and inner classes are normally private. We’re using a named inner class instead of an anonymous inner class because named inner classes are slightly more flexible. They allow you to create a listener that’s used on more than one component. We’ll provide an example in an upcoming program.
To register the above listener with our helloButton component, do this: helloButton.addActionListener(new Listener());
b
b
u
ut
t
t
to
on
nl
la
ab
b
e
e
l
l
’
’
s
st
te
e
x
xt
t
When this button is displayed, it says “Press me” in the center of the button. The label argument is optional.