// SimpleFinCalculator.java
// Crude financial calculator
// Basics of simple GUI components
// APPLET CODE="SimpleFinCalculator" HEIGHT=200 WIDTH=680
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;

public class SimpleFinCalculator extends JApplet implements ActionListener {
	Font f;
	DecimalFormat dollars;

	// Financial variable
	double v;

	// GUI components
	Container c;
	JLabel title, lAmount, lIRate, lPeriods, lResult;
	JTextField inAmount, inIRate, inPeriods, outResult;
	JButton bPV, bFV;

	public void init( ) {
		f = new Font( "Arial", Font.BOLD + Font.ITALIC, 36 );
		dollars = new DecimalFormat( "$0.00" );

		c = getContentPane( );
		c.setLayout( new FlowLayout( ) );
		title = new JLabel( "Financial Calculator" );
		title.setFont( f );
		c.add( title );
		lAmount = new JLabel( "Amount" );
		c.add( lAmount );
		inAmount = new JTextField( 10 );
		c.add( inAmount );
		lIRate = new JLabel( "Int Rate" );
		c.add( lIRate );
		inIRate = new JTextField( 10 );
		c.add( inIRate );
		lPeriods = new JLabel( "Periods" );
		c.add( lPeriods );
		inPeriods = new JTextField( 10 );
		c.add( inPeriods );		
		lResult = new JLabel( "Result:  " );
		c.add( lResult );
		outResult = new JTextField( 10 );
		outResult.setEditable( false );
		c.add( outResult );
		Icon money1 = new ImageIcon( "Bizg.gif" );
		bPV = new JButton( "PV", money1 );
		c.add( bPV );
		Icon money2 = new ImageIcon( "Moneybag.gif" );
		bFV = new JButton( "FV", money2 );
		c.add( bFV );

		// register the applet as the action listener
		bPV.addActionListener( this );
		bFV.addActionListener( this );
	}

	public void actionPerformed( ActionEvent e ) {
		// turn text into values
		double amt = Double.parseDouble( inAmount.getText( ) );
		double iRate = Double.parseDouble( inIRate.getText( ) );
		int nPer = Integer.parseInt( inPeriods.getText( ) );
			
		if ( e.getSource( ) == bPV )
			v = pv( amt, iRate, nPer );
		else
			v = fv( amt, iRate, nPer );

		outResult.setText( dollars.format( v ) );
	}

	double pv( double a, double i, int n ) {
		return a / ( Math.pow( 1 + i, n ) );
	}

	double fv( double a, double i, int n ) {
		return a * ( Math.pow( 1 + i, n ) );
	}
}