Building Applications with Buttons
Example: investment viewer program; whenever button is clicked, interest is added, and new balance is displayed
Construct an object of the JButton class:
JButton button = new JButton("Add Interest");
We need a user interface component that displays a message
JLabel label = new JLabel("balance: " + account.getBalance());
Use a JPanel container to group multiple user interface components together:
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
frame.add(panel);
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());
}
}
Add
AddInterestListener
as
inner
class so it can have access
to surrounding
final
variables (account
and
label)
Click here to see the example.
How do you place the "balance: . . ." message to the left of the "Add Interest" button?
Answer: First add label to the panel, then add button
Why was it not necessary to declare the button variable as final?
Answer: The actionPerformed method does not access that variable.