Java GUI Calculator

Write Calculator which uses user input to calculate monthly payment

Page 1 of 1

4 Replies - 28167 Views - Last Post: 24 April 2010 - 09:53 AM Rate Topic: -----

#1 JoeJo   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 23-April 10

Java GUI Calculator

Posted 23 April 2010 - 06:05 PM

I had posted this just now; but i was advised to open my own thread. so...

Here is what I have to do...

Write the program in Java (with a graphical user interface) and have it calculate and display the
mortgage payment amount from user input of the amount of the mortgage and the user's
selection from a menu of available mortgage loans:
- 7 years at 5.35%
- 15 years at 5.5%
- 30 years at 5.75%

Use an array for the mortgage data for the different loans. Display the mortgage payment
amount followed by the loan balance and interest paid for each payment over the term of the
loan. Allow the user to loop back and enter a new amount and make a new selection or quit.

I tackled this before but then i wasn't required to provided a GUI; the mortgage loans were hard coded

I plan to use radio buttons to handle the selection process; but i am not quite there yet. I want to first accomplish this...

Write the program in Java (with a graphical user interface) and have it calculate and display the
mortgage payment amount from user input of the amount of the mortgage, the term of the
mortgage, and the interest rate of the mortgage.

Here is what i wrote

import javax.swing.JFrame; 
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class MortgageCalculator extends JFrame
{
	
		//declare the width & height of the calculator
		private static final int Width = 300;
		private static final int Height = 300;
		//declare the labels for the calculators text fields
		public JLabel MAmount;
		private JLabel MRate;
		private JLabel MTime;
		private JLabel MPayment;
		//declare the text fields for the calculator
		private JTextField Loan;
		private JTextField Interest;
		private JTextField Term;
		private JTextField MonthlyP;
		//declare the calculator's button
		private JButton CalculateButt;
		private JButton ResetButt;
		private JButton ExitButt;
						
		public MortgageCalculator(){
				
				//create instanses of the text field's labels
				MAmount = new JLabel("Enter the Principle: ", SwingConstants.RIGHT);
            MRate = new JLabel("Enter the Rate: ", SwingConstants.RIGHT);
            MTime = new JLabel("Enter the Term: ", SwingConstants.RIGHT);
            MPayment = new JLabel("Monthly Payment: ", SwingConstants.RIGHT);
				//create instanses of the calculator's text fields
				Loan = new JTextField(5);
            Interest = new JTextField(5);
            Term = new JTextField(5);
            MonthlyP = new JTextField(5);
				//SPecify handlers for each button and add (register) ActionListeners to each button.
            CalculateButt = new JButton("Calculate");
            CalcB = new CalculateButtonHandler();
            CalculateButt.addActionListener(CalcB);
            ResetButt = new JButton("Reset");
            Refresh = new ResetButtonHandler();
            ResetButt.addActionListener(Refresh);
				ExitButt = new JButton("Exit");
				CloseOut = new ExitButtonHandler();
				ExitButt.addActionListener(CloseOut);
				//create instances of the calculator's buttons
            CalculateButt = new JButton("Calculate");
            ResetButt = new JButton("Reset");
				ExitButt = JButton("Exit");	
				//sets the title of the frame
				setTitle("Change Request 5");
				//get the content pane
				Container pane = getContentPane();
				//set the layout
				pane.setLayout(new Gridlayout (4,2));
				//Add the labels and text fields to the pane in the order you want them to appear (left to right, top to bottom)
            pane.add(MAmount);
            pane.add(MRate);
            pane.add(MTime);
            pane.add(MPayment);
            pane.add(Loan);
            pane.add(Interest);
            pane.add(Term);
            pane.add(MonthlyP);
				pand.add(CalculateButt);
				pane.add(ResetButt);
				pane.add(ExitButt);
				//sets the dimensions of the window
				setSize(WIDTH, HEIGHT);
				//allows the user to see the window on screen
				setVisible("true");
				//defines how the window will act when the "X" is pressed
				setDefaultCloseOperation(EXIT_ON_CLOSE);
				}
private class CalculateButtonHandler implements ActionListener
{
              public void actionPerformed(ActionEvent e)
              {
                       // declare new variables which will hold user input & calculated result 
								double P, R, T;
                        //tells the program which user input to pass to which of the declared variables
								//We use the getText & setText methods to manipulate the data entered into those fields
                        P = Double.parseDouble(Loan.getText()); 
                        R = Double.parseDouble(Interest.getText())/12;
                        T = Double.parseDouble(Term.getText())*12;
								//calculate the monthly payment
								MonthlyP = P*Math.pow(1+R,N)*R/(Math.pow(1+R,N)-1);
								MonthlyP.setText("" + MonthlyP);
					}

}
private class ResetButtonHandler implements ActionListener
					{
     		      public void actionPerformed(ActionEvent e)
					{
						Loan.setText("");
						Rate.setText("");
						Term.setText("");
						MonthlyP.setText("");
			      }
}
public class ExitButtonHandler implements ActionListener
        {
                public void actionPerformed(ActionEvent e)
                {
                        System.exit(0);
                }
        }
        
        public static void main(String[] args)
        {
                MortgageCalculator mortObj = new MortgageCalculator();
        }
        
}			



The errors (14) i am getting are:


 ----jGRASP exec: javac -g C:\Users\JOEJ03\Documents\JGrasp\MortgageCalculator\MortgageCalculator.java

MortgageCalculator.java:41: cannot find symbol
symbol  : variable CalcB
location: class MortgageCalculator
            CalcB = new CalculateButtonHandler();
            ^
MortgageCalculator.java:42: cannot find symbol
symbol  : variable CalcB
location: class MortgageCalculator
            CalculateButt.addActionListener(CalcB);
                                            ^
MortgageCalculator.java:44: cannot find symbol
symbol  : variable Refresh
location: class MortgageCalculator
            Refresh = new ResetButtonHandler();
            ^
MortgageCalculator.java:45: cannot find symbol
symbol  : variable Refresh
location: class MortgageCalculator
            ResetButt.addActionListener(Refresh);
                                        ^
MortgageCalculator.java:47: cannot find symbol
symbol  : variable CloseOut
location: class MortgageCalculator
				CloseOut = new ExitButtonHandler();
				^
MortgageCalculator.java:48: cannot find symbol
symbol  : variable CloseOut
location: class MortgageCalculator
				ExitButt.addActionListener(CloseOut);
				                           ^
MortgageCalculator.java:52: cannot find symbol
symbol  : method JButton(java.lang.String)
location: class MortgageCalculator
				ExitButt = JButton("Exit");	
				           ^
MortgageCalculator.java:58: cannot find symbol
symbol  : class Gridlayout
location: class MortgageCalculator
				pane.setLayout(new Gridlayout (4,2));
				                   ^
MortgageCalculator.java:68: cannot find symbol
symbol  : variable pand
location: class MortgageCalculator
				pand.add(CalculateButt);
				^
MortgageCalculator.java:74: cannot find symbol
symbol  : method setVisible(java.lang.String)
location: class MortgageCalculator
				setVisible("true");
				^
MortgageCalculator.java:90: cannot find symbol
symbol  : variable N
location: class MortgageCalculator.CalculateButtonHandler
								MonthlyP = P*Math.pow(1+R,N)*R/(Math.pow(1+R,N)-1);
								                          ^
MortgageCalculator.java:90: cannot find symbol
symbol  : variable N
location: class MortgageCalculator.CalculateButtonHandler
								MonthlyP = P*Math.pow(1+R,N)*R/(Math.pow(1+R,N)-1);
								                                             ^
MortgageCalculator.java:90: incompatible types
found   : double
required: javax.swing.JTextField
								MonthlyP = P*Math.pow(1+R,N)*R/(Math.pow(1+R,N)-1);
								                              ^
MortgageCalculator.java:100: cannot find symbol
symbol  : variable Rate
location: class MortgageCalculator.ResetButtonHandler
						Rate.setText("");
						^
14 errors

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.



It seems these errors are cascading so if i fix a few the rest should go; i can not pick up why i am getting these errors.

Is This A Good Question/Topic? 0
  • +

Replies To: Java GUI Calculator

#2 ianian112   User is offline

  • D.I.C Regular
  • member icon

Reputation: 119
  • View blog
  • Posts: 378
  • Joined: 28-November 09

Re: Java GUI Calculator

Posted 23 April 2010 - 06:19 PM

 CalculateButt = new JButton("Calculate");
            CalcB = new CalculateButtonHandler();
            CalculateButt.addActionListener(CalcB);
            ResetButt = new JButton("Reset");
            Refresh = new ResetButtonHandler();
            ResetButt.addActionListener(Refresh);


I dont see CalcB declared ever you could go
CalculateButtonHandler  CalcB = new CalculateButtonHandler();

or maybe
CalculateButt.addActionListener(new CalculateButtonHandler());

Same with your other errors.

This post has been edited by ianian112: 23 April 2010 - 06:19 PM

Was This Post Helpful? 0
  • +
  • -

#3 JoeJo   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 23-April 10

Re: Java GUI Calculator

Posted 24 April 2010 - 06:32 AM

ok. I got 0 errors now but the layout is a mess.

import javax.swing.JFrame;
import javax.swing.JPanel; 
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;

public class MortgageCalculator extends JFrame
{
	//declare the width & height of the calculator
	private static final int Width = 300;
	private static final int Height = 300;
				
//create instanses of the text field's labels
JLabel MAmount = new JLabel("Enter the Principle: ", SwingConstants.RIGHT);
JLabel MRate = new JLabel("Enter the Rate: ", SwingConstants.RIGHT);
JLabel MTime = new JLabel("Enter the Term: ", SwingConstants.RIGHT);
JLabel MPayment = new JLabel("Monthly Payment: ", SwingConstants.RIGHT);
//create instanses of the calculator's text fields
	JTextField Loan = new JTextField(5);
        JTextField Interest = new JTextField(5);
        JTextField Term = new JTextField(5);
        JTextField MonthlyP = new JTextField(5);
	//create instances of the calculator's buttons
           JButton CalculateButt = new JButton("Calculate");
           JButton ResetButt = new JButton("Reset");
	   JButton ExitButt = new JButton("Exit");

public MortgageCalculator(){
				
    //SPecify handlers for each button and add (register)    ActionListeners to each button.
            CalculateButt = new JButton("Calculate");
           	CalculateButtonHandler CalcB = new CalculateButtonHandler();
            CalculateButt.addActionListener(CalcB);
            ResetButt = new JButton("Reset");
            ResetButtonHandler Refresh = new ResetButtonHandler();
            ResetButt.addActionListener(Refresh);
				ExitButt = new JButton("Exit");
				ExitButtonHandler CloseOut = new ExitButtonHandler();
				ExitButt.addActionListener(CloseOut);
				//sets the title of the frame
				setTitle("Change Request 5");
				//get the content pane
					Container pane = getContentPane();
                pane.setLayout(new GridLayout(4, 2));
				//Add the labels and text fields to the pane in the order you want them to appear (left to right, top to bottom)
            pane.add(MAmount);
            pane.add(MRate);
            pane.add(MTime);
            pane.add(MPayment);
            pane.add(Loan);
            pane.add(Interest);
            pane.add(Term);
            pane.add(MonthlyP);
				pane.add(CalculateButt);
				pane.add(ResetButt);
				pane.add(ExitButt);
				//sets the dimensions of the window
				setSize(WIDTH, HEIGHT);
				//allows the user to see the window on screen
				setVisible(true);
				//defines how the window will act when the "X" is pressed
				setDefaultCloseOperation(EXIT_ON_CLOSE);
				}
private class CalculateButtonHandler implements ActionListener
{
              public void actionPerformed(ActionEvent e)
              {
                       // declare new variables which will hold user input & calculated result 
								double P, R, T, MP;
                        //tells the program which user input to pass to which of the declared variables
								//We use the getText & setText methods to manipulate the data entered into those fields
                        P = Double.parseDouble(Loan.getText()); 
                        R = Double.parseDouble(Interest.getText())/12;
                        T = Double.parseDouble(Term.getText())*12;
								//calculate the monthly payment
								MP = P*Math.pow(1+R,T)*R/(Math.pow(1+R,T)-1);
								MonthlyP.setText("" + MP);
					}

}
private class ResetButtonHandler implements ActionListener
					{
     		      public void actionPerformed(ActionEvent e)
					{
						Loan.setText("");
						Interest.setText("");
						Term.setText("");
						MonthlyP.setText("");
			      }
}
public class ExitButtonHandler implements ActionListener
        {
                public void actionPerformed(ActionEvent e)
                {
                        System.exit(0);
                }
        }
        
        public static void main(String[] args)
        {
                MortgageCalculator mortObj = new MortgageCalculator();
        }
        
}			



Can some help me with this layout; when i run the window opens very small :oops:

This post has been edited by JoeJo: 24 April 2010 - 06:47 AM

Was This Post Helpful? 0
  • +
  • -

#4 ballerplaya   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 05-April 10

Re: Java GUI Calculator

Posted 24 April 2010 - 07:32 AM

Add

this.setSize(x,y);

Was This Post Helpful? 0
  • +
  • -

#5 JoeJo   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 23-April 10

Re: Java GUI Calculator

Posted 24 April 2010 - 09:53 AM

I am now attempting to add a text area and get amortization table to show in that text area when the calculate button is clicked.

here is the full program

import javax.swing.JFrame;
import javax.swing.JPanel; 
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;

public class MortgageCalculator extends JFrame
{
				//create instanses of the text field's labels
				JLabel MAmount = new JLabel("Principle:");
            JLabel MRate = new JLabel("Rate:");
            JLabel MTime = new JLabel("Term:");
            JLabel MPayment = new JLabel("Payment");
				//create instanses of the calculator's text fields
				JTextField Loan = new JTextField();
            JTextField Interest = new JTextField();
            JTextField Term = new JTextField();
           	JTextField MonthlyP = new JTextField();
				//creates a text area
				JTextArea txtArea = new JTextArea();
				//create instances of the calculator's buttons
           	JButton CalculateButt = new JButton("Calculate");
            JButton ResetButt = new JButton("Reset");
				JButton ExitButt = new JButton("Exit");

		public MortgageCalculator(){
				
				//SPecify handlers for each button and add (register) ActionListeners to each button.
            CalculateButt = new JButton("Calculate");
           	CalculateButtonHandler CalcB = new CalculateButtonHandler();
            CalculateButt.addActionListener(CalcB);
            ResetButt = new JButton("Reset");
            ResetButtonHandler Refresh = new ResetButtonHandler();
            ResetButt.addActionListener(Refresh);
				ExitButt = new JButton("Exit");
				ExitButtonHandler CloseOut = new ExitButtonHandler();
				ExitButt.addActionListener(CloseOut);
				//sets the title of the frame
				setTitle("Change Request 5");
				//makes the text area scrollable
				JScrollPane scrollPane = new JScrollPane(txtArea); 
				txtArea.setEditable(true);

				
				//create the GridLayout for the text boxes and labels & buttond
				Container pane = getContentPane();
            pane.setLayout(new GridLayout(11,3));
				pane.add(MAmount);
				pane.add(Loan);
            pane.add(MRate);
				pane.add(Interest);
            pane.add(MTime);
				pane.add(Term);
            pane.add(MPayment);
            pane.add(MonthlyP);
				pane.add(CalculateButt);
				pane.add(ResetButt);
				pane.add(ExitButt);
				pane.add(txtArea);
				//sets the dimensions of the window
				this.setSize(200, 200);
				//allows the user to see the window on screen
				setVisible(true);
				//defines how the window will act when the "X" is pressed
				setDefaultCloseOperation(EXIT_ON_CLOSE);
				}
private class CalculateButtonHandler implements ActionListener
{
              public void actionPerformed(ActionEvent e)
              {
                       // declare new variables which will hold user input & calculated result 
								double P, R, T, MP;
                        //tells the program which user input to pass to which of the declared variables
								//We use the getText & setText methods to manipulate the data entered into those fields
                        P = Double.parseDouble(Loan.getText()); 
                        R = Double.parseDouble(Interest.getText())/100/12;
                        T = Double.parseDouble(Term.getText())*12;
								//calculate the monthly payment
								MP = P*Math.pow(1+R,T)*R/(Math.pow(1+R,T)-1);
								
								MonthlyP.setText("" + MP);
							
					
					// Amoritization Table Header
		      	System.out.printf("\n\n\n\t\t\t\tMortgage Amoritization Table\n\n");

					// Amoritization Table Column Headings
			  		 System.out.printf("Month No.\t\tMonthly Payment\t\tRemaining Balance\t\tInterest Paid\n");
					 
					 	// set remaining balance to the original loan principle
            		double OutstandingBalance = P;
						// loop through months in the loan plan
			   		for(int y=0; y<=T; y++){
           			 double CurrentPaymentInterest = R * OutstandingBalance; // calculate interest for current payment
						double CurrentPaymentPrincipal = T - CurrentPaymentInterest; // calculate the principle for current payment
						OutstandingBalance = OutstandingBalance - CurrentPaymentPrincipal; // calculate the total remaining balance

				// Outputs the monthly amounts to the screen under their Amoritization Table Headings
				System.out.printf("%3d\t\t\t%.2f\t\t\t%.2f\t\t\t%.2f\n", y , T , OutstandingBalance , CurrentPaymentInterest);

				// loop to break after every 50th row and asks user to press enter to continue
				if(y % 50 == 0){
				String TempHolder = null;
				System.out.printf("Press the ENTER key to continue...");
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
					try{
						TempHolder = br.readLine();
					} catch(IOException e){
						System.out.println("There has been an error");
						System.exit(1);
							}
						}
					}


}
private class ResetButtonHandler implements ActionListener
					{
     		      public void actionPerformed(ActionEvent e)
					{
						Loan.setText("");
						Interest.setText("");
						Term.setText("");
						MonthlyP.setText("");
						txtArea.setText("");
			      }
}
public class ExitButtonHandler implements ActionListener
        {
                public void actionPerformed(ActionEvent e)
                {
                        System.exit(1);
                }
        }
        
        public static void main(String[] args)
        {
                MortgageCalculator mortObj = new MortgageCalculator();
        }
	}
}        



Here is the code for the amortization table

					// Amoritization Table Header
		      	System.out.printf("\n\n\n\t\t\t\tMortgage Amoritization Table\n\n");

					// Amoritization Table Column Headings
			  		 System.out.printf("Month No.\t\tMonthly Payment\t\tRemaining Balance\t\tInterest Paid\n");
					 
					 	// set remaining balance to the original loan principle
            		double OutstandingBalance = P;
						// loop through months in the loan plan
			   		for(int y=0; y<=T; y++){
           			 double CurrentPaymentInterest = R * OutstandingBalance; // calculate interest for current payment
						double CurrentPaymentPrincipal = T - CurrentPaymentInterest; // calculate the principle for current payment
						OutstandingBalance = OutstandingBalance - CurrentPaymentPrincipal; // calculate the total remaining balance

				// Outputs the monthly amounts to the screen under their Amoritization Table Headings
				System.out.printf("%3d\t\t\t%.2f\t\t\t%.2f\t\t\t%.2f\n", y , T , OutstandingBalance , CurrentPaymentInterest);

				// loop to break after every 50th row and asks user to press enter to continue
				if(y % 50 == 0){
				String TempHolder = null;
				System.out.printf("Press the ENTER key to continue...");
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
					try{
						TempHolder = br.readLine();
					} catch(IOException e){
						System.out.println("There has been an error");
						System.exit(1);
							}
						}
					}


}



now what i do not get is that this code was finally working and showing acceptably and from the moment i added the amortization code
i got the following errors

                                             ^
MortgageCalculator.java:40: cannot find symbol
symbol  : class ExitButtonHandler
location: class MortgageCalculator
				ExitButtonHandler CloseOut = new ExitButtonHandler();
				^
MortgageCalculator.java:40: cannot find symbol
symbol  : class ExitButtonHandler
location: class MortgageCalculator
				ExitButtonHandler CloseOut = new ExitButtonHandler();
				                                 ^
MortgageCalculator.java:112: e is already defined in actionPerformed(java.awt.event.ActionEvent)
					} catch(IOException e){
					                    ^
MortgageCalculator.java:140: inner classes cannot have static declarations
        public static void main(String[] args)
                           ^
6 errors

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

 ----jGRASP exec: javac -g C:\Users\JOEJ03\Documents\JGrasp\MortgageCalculator\MortgageCalculator.java

MortgageCalculator.java:37: cannot find symbol
symbol  : class ResetButtonHandler
location: class MortgageCalculator
            ResetButtonHandler Refresh = new ResetButtonHandler();
            ^
MortgageCalculator.java:37: cannot find symbol
symbol  : class ResetButtonHandler
location: class MortgageCalculator
            ResetButtonHandler Refresh = new ResetButtonHandler();
                                             ^
MortgageCalculator.java:40: cannot find symbol
symbol  : class ExitButtonHandler
location: class MortgageCalculator
				ExitButtonHandler CloseOut = new ExitButtonHandler();
				^
MortgageCalculator.java:40: cannot find symbol
symbol  : class ExitButtonHandler
location: class MortgageCalculator
				ExitButtonHandler CloseOut = new ExitButtonHandler();
				                                 ^
MortgageCalculator.java:112: e is already defined in actionPerformed(java.awt.event.ActionEvent)
					} catch(IOException e){
					                    ^
MortgageCalculator.java:140: inner classes cannot have static declarations
        public static void main(String[] args)
                           ^
6 errors



so i need help in understanding and fixing two things

1. why would the addition of amortization code affect my buttons
2. how do i get the amortization to show in the text area

This post has been edited by JoeJo: 25 April 2010 - 09:41 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1