/* filename: maturity.java description: evaluates the amount on a certificate of deposit of maturity author: Kalin Ringkvist, k.rainquist@comcast.net version: 1.00 2004-02-10 */ //import Java classes import javax.swing.*; import java.awt.*; import java.awt.event.*;//to detect the click on the button import java.text.*; //to format our output public class maturity extends JFrame { //create instance variables private JLabel lblAmount = new JLabel("Amount deposited:"); private JLabel lblYears = new JLabel("Number of Years:"); private JLabel lblInterest = new JLabel("Interest rate:"); private JTextField txbAmount = new JTextField(""); private JTextField txbYears = new JTextField(""); private JTextField txbInterest = new JTextField(""); private JTextField txbResult = new JTextField(""); private JButton butCalc = new JButton("Calculate"); private CalculateButtonHandler calcHandler; public maturity() { //get reference to JFrame. Container frame = getContentPane(); //create and apply layout to the frame frame.setLayout(new GridLayout(4,2)); //set result box as uneditable txbResult.setEditable(false); //set the default operation to exit when the user closes the application setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set the title of the frame setTitle("Calculate amount of a certificate of deposit on maturity."); //show the frame show(); //put the objects on the form & align text frame.add(lblAmount); lblAmount.setHorizontalAlignment(JTextField.CENTER); frame.add(txbAmount); frame.add(lblYears); lblYears.setHorizontalAlignment(JTextField.CENTER); frame.add(txbYears); frame.add(lblInterest); lblInterest.setHorizontalAlignment(JTextField.CENTER); frame.add(txbInterest); frame.add(butCalc); frame.add(txbResult); //add action listener to butCalc to detect the click calcHandler = new CalculateButtonHandler(); butCalc.addActionListener(calcHandler); } public static void main(String[] args) { maturity m = new maturity(); //instantiate class m.pack(); //pack the frame around the objects } //private class handles the button click event private class CalculateButtonHandler implements ActionListener { public void actionPerformed(ActionEvent event) { //get the user input double amount = Double.parseDouble(txbAmount.getText()); double years = Double.parseDouble(txbYears.getText()); double rate = Double.parseDouble(txbInterest.getText()); //calculate total amount and put into result double result = amount * (Math.pow(1 + rate / 100, years)); //format and display the result NumberFormat formatter = NumberFormat.getCurrencyInstance(); txbResult.setText(formatter.format(result)); } } }