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     A frame that shows the growth of an investment with variable interest.
 11  */
 12  public class InvestmentFrame extends JFrame
 13  {    
 14     private static final int FRAME_WIDTH = 450;
 15     private static final int FRAME_HEIGHT = 100;
 16  
 17     private static final double DEFAULT_RATE = 5;
 18     private static final double INITIAL_BALANCE = 1000;   
 19  
 20     private JLabel rateLabel;
 21     private JTextField rateField;
 22     private JButton button;
 23     private JLabel resultLabel;
 24     private JPanel panel;
 25     private BankAccount account;
 26   
 27     public InvestmentFrame()
 28     {  
 29        account = new BankAccount(INITIAL_BALANCE);
 30  
 31        // Use instance variables for components 
 32        resultLabel = new JLabel("balance: " + account.getBalance());
 33  
 34        // Use helper methods 
 35        createTextField();
 36        createButton();
 37        createPanel();
 38  
 39        setSize(FRAME_WIDTH, FRAME_HEIGHT);
 40     }
 41  
 42     private void createTextField()
 43     {
 44        rateLabel = new JLabel("Interest Rate: ");
 45  
 46        final int FIELD_WIDTH = 10;
 47        rateField = new JTextField(FIELD_WIDTH);
 48        rateField.setText("" + DEFAULT_RATE);
 49     }
 50     
 51     private void createButton()
 52     {
 53        button = new JButton("Add Interest");
 54        
 55        class AddInterestListener implements ActionListener
 56        {
 57           public void actionPerformed(ActionEvent event)
 58           {
 59              double rate = Double.parseDouble(rateField.getText());
 60              double interest = account.getBalance() * rate / 100;
 61              account.deposit(interest);
 62              resultLabel.setText("balance: " + account.getBalance());
 63           }            
 64        }
 65        
 66        ActionListener listener = new AddInterestListener();
 67        button.addActionListener(listener);
 68     }
 69  
 70     private void createPanel()
 71     {
 72        panel = new JPanel();
 73        panel.add(rateLabel);
 74        panel.add(rateField);
 75        panel.add(button);
 76        panel.add(resultLabel);      
 77        add(panel);
 78     } 
 79  }