Java Reference
In-Depth Information
top of each other. The solution is to put them into a panel, a container for other
user-interface components, and then add the panel to the frame:
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
frame.add(panel);
Use a JPanel container to group multiple user-interface components together.
Now we are ready for the hard partÈŒthe event listener that handles button clicks. As
in the preceding section, it is necessary to define a class that implements the
ActionListener interface, and to place the button action into the
actionPerformed method. Our listener class adds interest and displays the new
balance:
class AddInterestListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
double interest = account.getBalance() *
INTEREST_RATE / 100;
account.deposit(interest);
label.setText("balance: " +
account.getBalance());
}
}
There is just a minor technicality. The actionPerformed method manipulates the
account and label variables. These are local variables of the main method of the
investment viewer program, not instance fields of the AddInterestListener
class. We therefore need to declare the account and label variables as final so
that the actionPerformed method can access them.
You often install event listeners as inner classes so that they can have access to the
surrounding fields, methods, and final variables.
Let's put the pieces together.
public static void main(String[] args)
{
Search WWH ::




Custom Search