Java Reference
In-Depth Information
S
ELF
C
HECK
15.
Why would an inner class method want to access a variable from a
surrounding scope?
16.
If an inner class accesses a local variable from a surrounding scope,
what special rule applies?
9.8 Building Applications with Buttons
In this section, you will learn how to structure a graphical application that contains
buttons. We will put a button to work in our simple investment viewer program.
Whenever the button is clicked, interest is added to a bank account, and the new
balance is displayed (see
Figure 4
).
First, we construct an object of the
JButton
class. Pass the button label to the
constructor:
JButton button = new JButton(
"Add Interest"
);
We also need a user interface component that displays a message, namely the current
bank balance. Such a component is called a label. You pass the initial message string
to the
JLabel
constructor, like this:
JLabel label = new JLabel("balance: " +
account.getBalance());
Figure 4
An Application with a Button
414
415
The frame of our application contains both the button and the label. However, we
cannot simply add both components directly to the frameČthey would be placed on