Java Reference
In-Depth Information
. . .
JButton button = new JButton("Add Interest");
final BankAccount account = new
BankAccount(INITIAL_BALANCE);
final JLabel label = new JLabel("balance: " +
account.getBalance());
class AddInterestListener implements
ActionListener
{
public void actionPerformed(ActionEvent event)
{
double interest = account.getBalance()
* INTEREST_RATE / 100;
account.deposit(interest);
label.setText("balance: " +
account.getBalance());
}
}
ActionListener listener = new
AddInterestListener();
button.addActionListener(listener);
. . .
}
415
416
With a bit of practice, you will learn to glance at this code and translate it into plain
English: ȒWhen the button is clicked, add interest and set the label text.ȓ
Here is the complete program. It demonstrates how to add multiple components to a
frame, by using a panel, and how to implement listeners as inner classes.
ch09/button3/InvestmentViewer2.java
1 import java.awt.event.ActionEvent;
2 import java.awt.event.ActionListener;
3 import javax.swing.JButton;
4 import javax.swing.JFrame;
5 import javax.swing.JLabel;
6 import javax.swing.JPanel;
7 import javax.swing.JTextField;
8
9 /**
10 This program displays the growth of an investment.
11 */
12 public class InvestmentViewer2
Search WWH ::




Custom Search