/* Example to illustrate the ActionListener interface: write an applet to compute the balance of an investment specified by the user, for a period of time and rate also specified by the user. The formula for computing the balance is principal * (1 + rate) ^ years. Adapted from Deitel & Deitel */ import java.awt.*; import java.awt.event.*; import java.applet.Applet; import java.text.*; public class Balance extends Applet implements ActionListener { double balance, principal, rate; int years; Label label1, label2, label3, title; TextField input1, input2, input3; public void init () { title = new Label ("Balance calculator"); label1 = new Label ("Enter principal: "); label2 = new Label ("Enter rate: "); label3 = new Label ("Enter period of time (in years): "); input1 = new TextField (8); input2 = new TextField (8); input3 = new TextField (8); add (title); add (label1); add (input1); add (label2); add (input2); add (label3); add (input3); input3.addActionListener(this); balance = 0; rate = 0; years = 0; } public void paint ( Graphics g ) { int yPos = 240; DecimalFormat precisionTwo = new DecimalFormat( "#.00" ); g.drawString( "Year", 25, 185 ); g.drawString( "Amount on deposit", 100, 185 ); for ( int year = 1; year <= years; year++ ) { balance = principal * Math.pow( 1.0 + rate, year ); g.drawString( Integer.toString( year ), 25, yPos ); g.drawString( precisionTwo.format(balance), 100, yPos ); yPos += 15; } } public void actionPerformed (ActionEvent e) { principal = new Double (input1.getText()).doubleValue(); rate = new Double (input2.getText()).doubleValue(); years = Integer.parseInt(input3.getText()); repaint(); } }