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 InvestmentFrame2 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 double balance;
 25   
 26     public InvestmentFrame2()
 27     {  
 28        balance = INITIAL_BALANCE;
 29  
 30        resultLabel = new JLabel("Balance: " + balance);
 31  
 32        createTextField();
 33        createButton();
 34        createPanel();
 35  
 36        setSize(FRAME_WIDTH, FRAME_HEIGHT);
 37     }
 38  
 39     private void createTextField()
 40     {
 41        rateLabel = new JLabel("Interest Rate: ");
 42  
 43        final int FIELD_WIDTH = 10;
 44        rateField = new JTextField(FIELD_WIDTH);
 45        rateField.setText("" + DEFAULT_RATE);
 46     }
 47  
 48     /**
 49        Adds interest to the balance and updates the display.
 50     */
 51     class AddInterestListener implements ActionListener
 52     {
 53        public void actionPerformed(ActionEvent event)
 54        {
 55           double rate = Double.parseDouble(rateField.getText());
 56           double interest = balance * rate / 100;
 57           balance = balance + interest;
 58           resultLabel.setText("Balance: " + balance);
 59        }            
 60     }
 61        
 62     private void createButton()
 63     {
 64        button = new JButton("Add Interest");
 65        
 66        ActionListener listener = new AddInterestListener();
 67        button.addActionListener(listener);
 68     }
 69  
 70     private void createPanel()
 71     {
 72        JPanel panel = new JPanel();
 73        panel.add(rateLabel);
 74        panel.add(rateField);
 75        panel.add(button);
 76        panel.add(resultLabel);      
 77        add(panel);
 78     } 
 79  }