Buttons not performing correctly

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Eric Miles
    New Member
    • Feb 2012
    • 5

    Buttons not performing correctly

    My Mortgage Calculator program worked fine, until I added more functions. I added new fields for the new functions and changed my calculations for a calculate button, but it does not work. The rest of the program is fine. I commented out my else if exit command, because that would close my program when I hit the calculate button.

    Code:
    import java.awt.*;
    	import java.awt.event.*;
    	import javax.swing.*;
    	import java.text.DecimalFormat;
        import java.text.NumberFormat;
        public class MortgageCalculatorWeek3 {
    	
    		public static void main(String[] args) { // GUI JFrame Functions for Visibility and exit tool bar.
    			JFrame window = new Calculator ();
    			window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    			window.setVisible(true);
    	    }
        }
    		class Calculator extends JFrame implements ActionListener{ // Shows that the class Calculator extends the JFrame.		
    			
    			private static final long serialVersionUID = 1L; // Added to get rid of an error
    			private JButton Calculate, Calculate7, Calculate15, Calculate30, Clear, Exit; // Declares the buttons 
    		    private JLabel Payment, Principle, labelTitle, labelInstructions,AmortizationTable, Interest, Duration, LabelOr; // declares the JLables
    		    private JTextField fieldPayment, fieldLoanAmount, fieldInterest, fieldDuration; // Declares the JTextfields 
    		    private JTextArea areaAmortTable; // Declares the Amortization table text area. The area supports more lines than the JTextfield.		 
    		    
    		    //Declare variables and the loan array and assigns values. 
    		    double InterestPaid,PrinciplePaid,Balance,monthlyPay,loanAmount;
    		    int[] loanTerm = {7,15,30}; // Declares Loan terms
    		    double[] intRate = {5.35,5.50,5.75}; // Declares interest rates
    		    double loanAmt = loanAmount; // Declares area for user input for principle amount.
    			private DecimalFormat decimalPlaces; // sets decimal places for first calculate button
    			private DecimalFormat decimalPlaces2; // sets decimal places for second calculate button.
    			private DecimalFormat decimalPlaces3; // sets decimal places for third calculate button.
    			private DecimalFormat decimalPlaces4; 
    			private Dimension screenSize; // sets screen size.		     
    			int Months;
    			double Inter;
    			
    			
    		    public void actionPerformed (ActionEvent e)
    		    {
    		        //Provides looping functions for the buttons pressed.
    		    	if ("Calculate".equals(e.getActionCommand()))
    		    	{
    		    		setDecimalPlaces4(new DecimalFormat("0.00"));
    		    		NumberFormat currency = NumberFormat.getCurrencyInstance();
    		    		double paymentAmount = Calculate();
    		    		
    		    		
    		    		fieldPayment.setText("" + (currency.format(paymentAmount)));		 
    		            areaAmortTable.append ("Payment  \t Balance After Payment \t  Interest Paid\n");
    		    		
    		            loanAmt = Double.parseDouble(fieldLoanAmount.getText());
    		            for (int x = 1; x <=(Inter*12); x++){
    		            	Balance=loanAmt;
    		            	InterestPaid=(((Inter/100.0)/12.0)*Balance);
    		            	PrinciplePaid=(paymentAmount-InterestPaid);
    		            	loanAmt=(Balance-PrinciplePaid);
    		            	areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
    		            }
    		            if (Balance <= 0) //ending statement, balance at $0.00
    		            	areaAmortTable.append ("\tRemaining balance = $0.00");		                
    	            }
    		            {
    		    	}
    		          
    		           if ("Calculate7".equals(e.getActionCommand()))
    		        {
    		            setDecimalPlaces(new DecimalFormat("0.00"));
    		            NumberFormat currency = NumberFormat.getCurrencyInstance();		             
    		            double paymentAmount = CalculatePayment7();            
    		            
    		            fieldPayment.setText("" + (currency.format(paymentAmount)));		 
    		            areaAmortTable.append ("Payment  \t Balance After Payment \t  Interest Paid\n"); // sets fields for loan amortization table 
    		           
    		            loanAmt = Double.parseDouble(fieldLoanAmount.getText()); // allows user to input principle amount.		                     
    		            for (int x = 1; x <=(loanTerm[0]*12); x++) //Loop through all monthly payments for each loan
    		            {		                           
    		                    Balance=loanAmt; //Set Balance to Loan Amount                
    		                 
    		                    //Calculations on monthly payment		                     
    		                    InterestPaid=(((intRate[0]/100.0)/12.0)*Balance); //Monthly Interest paid
    		                    PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
    		                    loanAmt=(Balance-PrinciplePaid); //loan balance after payment	             
    		                               
    		                    areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
    		                    }	             
    		             
    		            if (Balance <= 0) //ending statement, balance at $0.00
    		            {
    		                areaAmortTable.append ("\tRemaining balance = $0.00");		                
    		            }
    		       }		 
    		        else if ("Calculate15".equals(e.getActionCommand())) // tells the first button what actions to perform.
    		        {
    		            setDecimalPlaces2(new DecimalFormat("0.00"));
    		            NumberFormat currency = NumberFormat.getCurrencyInstance();		             
    		            double paymentAmount = CalculatePayment15 ();		             
    		            fieldPayment.setText("" + (currency.format(paymentAmount))); 
    		 
    		            areaAmortTable.append ("Payment  \t Balance After Payment \t  Interest Paid\n");
    		            loanAmt = Double.parseDouble(fieldLoanAmount.getText());		             
    		            for (int x = 1; x <=(loanTerm[1]*12); x++) 
    		            {		 
    		                    Balance = loanAmt;		                 
    		                    //Calculations on monthly payment
    		                    InterestPaid=((intRate[1]/100/12)*Balance); //Monthly Interest paid
    		                    PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
    		                    loanAmt=((Balance-PrinciplePaid)); //loan balance after payment		 
    		                    areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
    		            }		 
    		            if (loanAmt <= 0) //ending statement, balance at $0.00
    		            {
    		                areaAmortTable.append ("\tRemaining balance = $0.00");		                
    		            }		 
    		        }		 
    		        else if ("Calculate30".equals(e.getActionCommand()))
    		        {
    		            setDecimalPlaces3(new DecimalFormat("0.00"));
    		            NumberFormat currency = NumberFormat.getCurrencyInstance();		             
    		            double paymentAmount = CalculatePayment30 ();		             
    		            fieldPayment.setText("" + (currency.format(paymentAmount)));		 
    		            areaAmortTable.append ("Payment \t Balance After Payment \t  Interest Paid\n");
    		            loanAmt = Double.parseDouble(fieldLoanAmount.getText());             
    		                     
    		            for (int x = 1; x <=(loanTerm[2]*12); x++) 
    		            {
    		                Balance = loanAmt;		 
    		                //Calculations on monthly payment
    		                InterestPaid=((intRate[2]/100/12)*Balance); //Monthly Interest paid
    		                PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
    		                loanAmt=((Balance-PrinciplePaid)); //loan balance after payment		 
    		                areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
    		            }		             
    		            if (loanAmt <= 0) //ending statement, balance at $0.00
    		            {
    		                areaAmortTable.append ("\tRemaining balance = $0.00");	                 
    		          
    		            }		 
    		        }
    		 
    		        else if ("Clear".equals(e.getActionCommand()))
    		        {
    		            ClearFields ();
    		        }
    		 
    		        else
    		        {		            
    		            //System.exit(0); //End and close application.
    		       }
    		    }
    		 
    		    public double CalculatePayment7 ()
    		    {    
    		       
    		        try //Check for number entry
    		        {
    	             //Perform payment calculations if input is valid
    		             
    		            fieldPayment.setText ("");
    		            double Payment =(loanAmount() * (intRate[0]/100/12)) / (1 - Math.pow(1/(1 + (intRate[0]/100/12)),loanTerm[0]*12));
    		            return Payment;
    		        }
    		 
    		        catch (NumberFormatException event)
    		        {
    		            //Display error message for invalid characters and beep at user.
    		        	 // beeps when there is an error
    		            JOptionPane.showMessageDialog(null, " Invalid entry, please enter numbers only", "ERROR", JOptionPane.ERROR_MESSAGE);
    		            System.out.print ( "\007" );
    		            return 0;
    		        }
    		    }
    		 
    		    public double CalculatePayment15 ()
    		    {
    		        
    		        try //Check for valid numeric input
    		        {
    		        	 //Display error message for invalid characters and beep at user.
    		            fieldPayment.setText ("");
    		            double Payment =(loanAmount() * (intRate[1]/100/12)) / (1 - Math.pow(1/(1 + (intRate[1]/100/12)),loanTerm[1]*12));
    		            return Payment;
    		        }
    		 
    		        catch (NumberFormatException event)
    		        {
    		        	 // Display error message for invalid characters and beep at user.
    		        	System.out.print ( "\007" ); // beeps when there is an error
    		            JOptionPane.showMessageDialog(null, " Invalid entry, please enter numbers only", "ERROR", JOptionPane.ERROR_MESSAGE);
    		            return 0;
    		        }
    		    }
    		 
    		    public double CalculatePayment30 ()
    		    {
    		        //Check for valid numeric input
    		        try
    		        {
    		            //Perform payment calculations if input is valid
    		            fieldPayment.setText ("");
    		            double Payment =(loanAmount() * (intRate[2]/100/12)) / (1 - Math.pow(1/(1 + (intRate[2]/100/12)),loanTerm[2]*12));
    		            return Payment;
    		        }
    		 
    		        catch (NumberFormatException event)
    		        {
    		            // Display error message for invalid characters and beep at user.
    		        	System.out.print ( "\007" ); // beeps when there is an error
    		            JOptionPane.showMessageDialog(null, " Invalid entry, please enter numbers only", "Error", JOptionPane.ERROR_MESSAGE);
    		            return 0;
    		        }
    		              	
    		    }
    		    public double Calculate(){
    		    	try{
    		    		
    		    	fieldPayment.setText("");
    		    	
    		    	double Payment =(loanAmount() * (Inter/100/12)) / (1 - Math.pow(1/(1 + (Inter/100/12)),Months*12));
    		    	return Payment;
    		    	
    		    	}
    		    	
    		    	catch (NumberFormatException event){
    		    		JOptionPane.showMessageDialog(null, "Invalid entry, please enter numbers only", "Error", JOptionPane.ERROR_MESSAGE);
    		    		return 0;
    		    	}
    		    }
    		 
    		 
    		    public void ClearFields ()
    		    {
    		        //clears all fields for new input.
    		        fieldPayment.setText ("");
    		        fieldLoanAmount.setText ("");
    		        areaAmortTable.setText ("");
    		        fieldInterest.setText ("");
    		        fieldDuration.setText (""); 
    		        
    		    }
    		 
    		    public Calculator ()
    		    {
    		        //Sets up buttons for GUI
    		    	Calculate = new JButton ("Calculate");
    		    	Calculate.setActionCommand ("Calculate");
    		        Calculate7 = new JButton ("7 Year, 5.35%");
    		        Calculate7.setActionCommand ("Calculate7");
    		        Calculate15 = new JButton ("15 Year, 5.50%");
    		        Calculate15.setActionCommand ("Calculate15");
    		        Calculate30 = new JButton ("30 Year, 5.75%");
    		        Calculate30.setActionCommand ("Calculate30");
    		        Clear = new JButton ("Clear ");
    		        Clear.setActionCommand ("Clear");
    		        Exit = new JButton ("Exit");
    		        Exit.setActionCommand ("Exit");
    		 
    		        //Set up labels and field sizes for GUI
    		        labelTitle = new JLabel ("Mortgage Amortization Calculator");
    		        labelInstructions = new JLabel ("Enter the Principle, Interest rate, and Loan Duration.");
    		        LabelOr = new JLabel (" Or Pick From These Loan Options After Entering Loan Amount");
    		        Payment = new JLabel ("Monthly Payment:");
    		        Principle = new JLabel ("Amount of Loan:");
    		        fieldPayment = new JTextField ("", 12);
    		        fieldLoanAmount = new JTextField ("", 10);
    		        AmortizationTable = new JLabel ("Amortization Table");
    		        areaAmortTable = new JTextArea (10, 300);
    		        Interest = new JLabel ("Interest Rate:");
    		        Duration = new JLabel ("Duration:");
    		        fieldInterest = new JTextField ("", 12);
    		        fieldDuration = new JTextField ("", 10);
    		        
    		        JScrollPane scrollPane = new JScrollPane (areaAmortTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    		        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    		 
    		        //Set up listeners for each button.
    		        Calculate.addActionListener(this);
    		        Calculate7.addActionListener(this);
    		        Calculate15.addActionListener(this);
    		        Calculate30.addActionListener(this);
    		        Clear.addActionListener(this);
    		        Exit.addActionListener(this);
    		 
    		        //Constructs GUI. 
    		        JPanel mine = new JPanel();
    		        mine.setLayout (null);
    		 
    		        mine.add (labelTitle);
    		        labelTitle.setBounds (110, 30, 700, 15);
    		 
    		        mine.add (labelInstructions);
    		        labelInstructions.setBounds (80, 70, 450, 15);
    		 
    		        mine.add (Principle);
    		        Principle.setBounds (130, 110, 100, 25);
    		        
    		        mine.add(Interest);
    		        Interest.setBounds (130 , 140, 120, 25);
    		        
    		        mine.add(Calculate);
    		        Calculate.setBounds(350, 145, 115, 25);
    		        
    		        mine.add(Duration);
    		        Duration.setBounds(130, 170, 120, 25);
    	 
    		        mine.add (fieldLoanAmount);
    		        fieldLoanAmount.setBounds (240, 110, 100, 25);
    		        
    		        mine.add(fieldInterest);
    		        fieldInterest.setBounds (240, 140, 100, 25);
    		        
    		        mine.add(fieldDuration);
    		        fieldDuration.setBounds (240, 170, 100, 25);
    		        
    		        mine.add(LabelOr);
    		        LabelOr.setBounds(80, 220, 400, 25);
    		 
    		        mine.add (Calculate7);
    		        Calculate7.setBounds (40, 260, 125, 30);
    		 
    		        mine.add (Calculate15);
    		        Calculate15.setBounds (180, 260, 125, 30);
    		 
    		        mine.add (Calculate30);
    		        Calculate30.setBounds (320, 260, 125, 30);
    		 
    		        mine.add (Payment);
    		        Payment.setBounds (130, 300, 100, 25);
    		 
    		        mine.add (fieldPayment);
    		        fieldPayment.setBounds (240, 300, 100, 25);
    		        fieldPayment.setEditable (false);
    		 
    		        mine.add (AmortizationTable);
    		        AmortizationTable.setBounds (180, 330, 300, 25);
    		 	 		        	 
    		         mine.add (scrollPane);
    		         scrollPane.setBounds (50, 350, 380, 260);
    		         areaAmortTable.setEditable(false);
    		 
    		         mine.add (Clear);
    		         Clear.setBounds (110, 620, 125, 30);
    		 
    	            mine.add (Exit);
    		        Exit.setBounds (250, 620, 125, 30);
    		 
    		        this.setContentPane(mine);
    		        this.pack();
    		        this.setTitle("Mortgage Amortization Calculator");
    		 
    		        setScreenSize(Toolkit.getDefaultToolkit().getScreenSize());
    		        setSize(500, 700);
    		    }
    		    public double loanAmount ()
    		    {
    		        double loanAmount = Double.parseDouble(fieldLoanAmount.getText());
    		        return loanAmount;
    		    }
    
    			public DecimalFormat getDecimalPlaces() {
    				return decimalPlaces;
    			}
    
    			public void setDecimalPlaces(DecimalFormat decimalPlaces) {
    				this.decimalPlaces = decimalPlaces;
    			}
    
    			public DecimalFormat getDecimalPlaces2() {
    				return decimalPlaces2;
    			}
    
    			public void setDecimalPlaces2(DecimalFormat decimalPlaces2) {
    				this.decimalPlaces2 = decimalPlaces2;
    			}
    			
    			public DecimalFormat getDecimalPlaces4() {
    				return decimalPlaces4;
    			}
    
    			public void setDecimalPlaces4(DecimalFormat decimalPlaces4) {
    				this.decimalPlaces4 = decimalPlaces4;
    			}
    
    			public Dimension getScreenSize() {
    				return screenSize;
    			}
    
    			public void setScreenSize(Dimension screenSize) {
    				this.screenSize = screenSize;
    			}
    
    			public DecimalFormat getDecimalPlaces3() {
    				return decimalPlaces3;
    			}
    
    			public void setDecimalPlaces3(DecimalFormat decimalPlaces3) {
    				this.decimalPlaces3 = decimalPlaces3;
    			}
    		}
    // end of program
  • neeraj0708
    New Member
    • Feb 2012
    • 21

    #2
    can u show us the code.. it will be more helpfull to understand.

    Comment

    • Eric Miles
      New Member
      • Feb 2012
      • 5

      #3
      Here is the code, so far. Most of the program works, but I added in 2 new fields (Interest, and Duration) and a calculate button. The program is supposed to give the user a choice on how to calculate the mortgage.

      Code:
      import java.awt.*;
      	import java.awt.event.*;
      	import javax.swing.*;
      
      	import java.text.DecimalFormat;
          import java.text.NumberFormat;
          
          public class MortgageCalculatorWeek3 {
      	
      		public static void main(String[] args) { // GUI JFrame Functions for Visibility and exit tool bar.
      			JFrame window = new Calculator ();
      			window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      			window.setVisible(true);
      	    }
          }
      		class Calculator extends JFrame implements ActionListener{ // Shows that the class Calculator extends the JFrame.		
      			
      			private static final long serialVersionUID = 1L; // Added to get rid of an error
      			private JButton Calculate, Calculate7, Calculate15, Calculate30, Clear, Exit; // Declares the buttons 
      		    private JLabel Payment, Principle, labelTitle, labelInstructions,AmortizationTable, Interest, Duration, LabelOr; // declares the JLables
      		    private JTextField fieldPayment, fieldLoanAmount, fieldInterest, fieldDuration; // Declares the JTextfields 
      		    private JTextArea areaAmortTable; // Declares the Amortization table text area. The area supports more lines than the JTextfield.		 
      		    
      		    //Declare variables and the loan array and assigns values. 
      		    double InterestPaid,PrinciplePaid,Balance,monthlyPay,loanAmount;
      		    int[] loanTerm = {7,15,30}; // Declares Loan terms
      		    double[] intRate = {5.35,5.50,5.75}; // Declares interest rates
      		    double loanAmt = loanAmount; // Declares area for user input for principle amount.
      			private DecimalFormat decimalPlaces; // sets decimal places for first calculate button
      			private DecimalFormat decimalPlaces2; // sets decimal places for second calculate button.
      			private DecimalFormat decimalPlaces3; // sets decimal places for third calculate button.
      			private DecimalFormat decimalPlaces4; 
      			private Dimension screenSize; // sets screen size.		     
      			double Inter, Months;
      			
      			
      		    @Override
      			public void actionPerformed (ActionEvent e)
      		    {
      		        
      		    	    if ("Calculate".equals(e.getActionCommand()))
      		    	{
      		    		setDecimalPlaces4(new DecimalFormat("0.00"));
      		    		NumberFormat currency = NumberFormat.getCurrencyInstance();
      		    		double paymentAmount = CalculatePayment();
      		    		
      		    		
      		    		fieldPayment.setText("" + (currency.format(paymentAmount)));		 
      		            areaAmortTable.append ("Payment  \t Balance After Payment \t  Interest Paid\n");
      		    		
      		            loanAmt = Double.parseDouble(fieldLoanAmount.getText());
      		            Months = Double.parseDouble(fieldDuration.getText());
      		            Inter = Double.parseDouble(fieldInterest.getText());
      		            
      		             
      		            for (int x = 1; x <=(Inter*12); x++){
      		            	Balance=loanAmt;
      		            	InterestPaid=(((Inter/100.0)/12.0)*Balance);
      		            	PrinciplePaid=(paymentAmount-InterestPaid);
      		            	loanAmt=(Balance-PrinciplePaid);
      		            	areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
      		            }
      		            if (Balance <= 0) //ending statement, balance at $0.00
      		            	areaAmortTable.append ("\tRemaining balance = $0.00");
      		            		           
      		    	}
      		          //Provides looping functions for the buttons pressed.
      		           if ("Calculate7".equals(e.getActionCommand()))
      		        {
      		            setDecimalPlaces(new DecimalFormat("0.00"));
      		            NumberFormat currency = NumberFormat.getCurrencyInstance();		             
      		            double paymentAmount = CalculatePayment7();            
      		            
      		            fieldPayment.setText("" + (currency.format(paymentAmount)));		 
      		            areaAmortTable.append ("Payment  \t Balance After Payment \t  Interest Paid\n"); // sets fields for loan amortization table 
      		           
      		            loanAmt = Double.parseDouble(fieldLoanAmount.getText()); // allows user to input principle amount.		                     
      		            for (int x = 1; x <=(loanTerm[0]*12); x++) //Loop through all monthly payments for each loan
      		            {		                           
      		                    Balance=loanAmt; //Set Balance to Loan Amount                
      		                 
      		                    //Calculations on monthly payment		                     
      		                    InterestPaid=(((intRate[0]/100.0)/12.0)*Balance); //Monthly Interest paid
      		                    PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
      		                    loanAmt=(Balance-PrinciplePaid); //loan balance after payment	             
      		                               
      		                    areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
      		                    }	             
      		             
      		            if (Balance <= 0) //ending statement, balance at $0.00
      		            {
      		                areaAmortTable.append ("\tRemaining balance = $0.00");		                
      		            }
      		       }		 
      		        else if ("Calculate15".equals(e.getActionCommand())) // tells the first button what actions to perform.
      		        {
      		            setDecimalPlaces2(new DecimalFormat("0.00"));
      		            NumberFormat currency = NumberFormat.getCurrencyInstance();		             
      		            double paymentAmount = CalculatePayment15 ();		             
      		            fieldPayment.setText("" + (currency.format(paymentAmount))); 
      		 
      		            areaAmortTable.append ("Payment  \t Balance After Payment \t  Interest Paid\n");
      		            loanAmt = Double.parseDouble(fieldLoanAmount.getText());		             
      		            for (int x = 1; x <=(loanTerm[1]*12); x++) 
      		            {		 
      		                    Balance = loanAmt;		                 
      		                    //Calculations on monthly payment
      		                    InterestPaid=((intRate[1]/100/12)*Balance); //Monthly Interest paid
      		                    PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
      		                    loanAmt=((Balance-PrinciplePaid)); //loan balance after payment		 
      		                    areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
      		            }		 
      		            if (loanAmt <= 0) //ending statement, balance at $0.00
      		            {
      		                areaAmortTable.append ("\tRemaining balance = $0.00");		                
      		            }		 
      		        }		 
      		        else if ("Calculate30".equals(e.getActionCommand()))
      		        {
      		            setDecimalPlaces3(new DecimalFormat("0.00"));
      		            NumberFormat currency = NumberFormat.getCurrencyInstance();		             
      		            double paymentAmount = CalculatePayment30 ();		             
      		            fieldPayment.setText("" + (currency.format(paymentAmount)));		 
      		            areaAmortTable.append ("Payment \t Balance After Payment \t  Interest Paid\n");
      		            loanAmt = Double.parseDouble(fieldLoanAmount.getText());             
      		                     
      		            for (int x = 1; x <=(loanTerm[2]*12); x++) 
      		            {
      		                Balance = loanAmt;		 
      		                //Calculations on monthly payment
      		                InterestPaid=((intRate[2]/100/12)*Balance); //Monthly Interest paid
      		                PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
      		                loanAmt=((Balance-PrinciplePaid)); //loan balance after payment		 
      		                areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n");
      		            }		             
      		            if (loanAmt <= 0) //ending statement, balance at $0.00
      		            {
      		                areaAmortTable.append ("\tRemaining balance = $0.00");	                 
      		          
      		            }		 
      		        }
      		 
      		        else if ("Clear".equals(e.getActionCommand()))
      		        {
      		            ClearFields ();
      		        }
      		 
      		        else
      		        {		            
      		            System.exit(0); //End and close application.
      		       }
      		    }
      		 
      		    public double CalculatePayment7 ()
      		    {    
      		       
      		        try //Check for number entry
      		        {
      	             //Perform payment calculations if input is valid
      		             
      		            fieldPayment.setText ("");
      		            double Payment =(loanAmount() * (intRate[0]/100/12)) / (1 - Math.pow(1/(1 + (intRate[0]/100/12)),loanTerm[0]*12));
      		            return Payment;
      		        }
      		 
      		        catch (NumberFormatException event)
      		        {
      		            //Display error message for invalid characters and beep at user.
      		        	 // beeps when there is an error
      		            JOptionPane.showMessageDialog(null, " Invalid entry, please enter numbers only", "ERROR", JOptionPane.ERROR_MESSAGE);
      		            System.out.print ( "\007" );
      		            return 0;
      		        }
      		    }
      		 
      		    public double CalculatePayment15 ()
      		    {
      		        
      		        try //Check for valid numeric input
      		        {
      		        	 //Display error message for invalid characters and beep at user.
      		            fieldPayment.setText ("");
      		            double Payment =(loanAmount() * (intRate[1]/100/12)) / (1 - Math.pow(1/(1 + (intRate[1]/100/12)),loanTerm[1]*12));
      		            return Payment;
      		        }
      		 
      		        catch (NumberFormatException event)
      		        {
      		        	 // Display error message for invalid characters and beep at user.
      		        	System.out.print ( "\007" ); // beeps when there is an error
      		            JOptionPane.showMessageDialog(null, " Invalid entry, please enter numbers only", "ERROR", JOptionPane.ERROR_MESSAGE);
      		            return 0;
      		        }
      		    }
      		 
      		    public double CalculatePayment30 ()
      		    {
      		        //Check for valid numeric input
      		        try
      		        {
      		            //Perform payment calculations if input is valid
      		            fieldPayment.setText ("");
      		            double Payment =(loanAmount() * (intRate[2]/100/12)) / (1 - Math.pow(1/(1 + (intRate[2]/100/12)),loanTerm[2]*12));
      		            return Payment;
      		        }
      		 
      		        catch (NumberFormatException event)
      		        {
      		            // Display error message for invalid characters and beep at user.
      		        	System.out.print ( "\007" ); // beeps when there is an error
      		            JOptionPane.showMessageDialog(null, " Invalid entry, please enter numbers only", "Error", JOptionPane.ERROR_MESSAGE);
      		            return 0;
      		        }
      		              	
      		    }
      		    public double CalculatePayment()
      		    {
      		    	try
      		    	{
      		    		
      		    	fieldPayment.setText("");
      		    	
      		    	double PaymentAmount =(loanAmount() * (Inter/100/12)) / (1 - Math.pow(1/(1 + (Inter/100/12)), Months * 12));
      		     	return PaymentAmount;
      		    	
      		    	}
      		    	
      		    	catch (NumberFormatException event)
      		    {
      		    		JOptionPane.showMessageDialog(null, "Invalid entry, please enter numbers only", "Error", JOptionPane.ERROR_MESSAGE);
      		   		    return 0;
      		    	}
      		    }
      		 
      		 
      		    public void ClearFields ()
      		    {
      		        //clears all fields for new input.
      		        fieldPayment.setText ("");
      		        fieldLoanAmount.setText ("");
      		        areaAmortTable.setText ("");
      		        fieldInterest.setText ("");
      		        fieldDuration.setText (""); 
      		        
      		    }
      		 
      		    public Calculator ()
      		    {
      		        //Sets up buttons for GUI
      		    	Calculate = new JButton ("Calculate");
      		    	Calculate.setActionCommand ("CalculatePayment");
      		        Calculate7 = new JButton ("7 Year, 5.35%");
      		        Calculate7.setActionCommand ("Calculate7");
      		        Calculate15 = new JButton ("15 Year, 5.50%");
      		        Calculate15.setActionCommand ("Calculate15");
      		        Calculate30 = new JButton ("30 Year, 5.75%");
      		        Calculate30.setActionCommand ("Calculate30");
      		        Clear = new JButton ("Clear ");
      		        Clear.setActionCommand ("Clear");
      		        Exit = new JButton ("Exit");
      		        Exit.setActionCommand ("Exit");
      		 
      		        //Set up labels and field sizes for GUI
      		        labelTitle = new JLabel ("Mortgage Amortization Calculator");
      		        labelInstructions = new JLabel ("Enter the Principle, Interest rate, and Loan Duration.");
      		        LabelOr = new JLabel (" Or Pick From These Loan Options After Entering Loan Amount");
      		        Payment = new JLabel ("Monthly Payment:");
      		        Principle = new JLabel ("Amount of Loan:");
      		        fieldPayment = new JTextField ("", 12);
      		        fieldLoanAmount = new JTextField ("", 10);
      		        AmortizationTable = new JLabel ("Amortization Table");
      		        areaAmortTable = new JTextArea (10, 300);
      		        Interest = new JLabel ("Interest Rate:");
      		        Duration = new JLabel ("Duration:");
      		        fieldInterest = new JTextField ("", 12);
      		        fieldDuration = new JTextField ("", 10);
      		        
      		        JScrollPane scrollPane = new JScrollPane (areaAmortTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
      		        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
      		 
      		        //Set up listeners for each button.
      		        Calculate.addActionListener(this);
      		        Calculate7.addActionListener(this);
      		        Calculate15.addActionListener(this);
      		        Calculate30.addActionListener(this);
      		        Clear.addActionListener(this);
      		        Exit.addActionListener(this);
      		 
      		        //Constructs GUI. 
      		        JPanel mine = new JPanel();
      		        mine.setLayout (null);
      		 
      		        mine.add (labelTitle);
      		        labelTitle.setBounds (110, 30, 700, 15);
      		 
      		        mine.add (labelInstructions);
      		        labelInstructions.setBounds (80, 70, 450, 15);
      		 
      		        mine.add (Principle);
      		        Principle.setBounds (130, 110, 100, 25);
      		        
      		        mine.add(Interest);
      		        Interest.setBounds (130 , 140, 120, 25);
      		        
      		        mine.add(Calculate);
      		        Calculate.setBounds(350, 145, 115, 25);
      		        
      		        mine.add(Duration);
      		        Duration.setBounds(130, 170, 120, 25);
      	 
      		        mine.add (fieldLoanAmount);
      		        fieldLoanAmount.setBounds (240, 110, 100, 25);
      		        
      		        mine.add(fieldInterest);
      		        fieldInterest.setBounds (240, 140, 100, 25);
      		        
      		        mine.add(fieldDuration);
      		        fieldDuration.setBounds (240, 170, 100, 25);
      		        
      		        mine.add(LabelOr);
      		        LabelOr.setBounds(80, 220, 400, 25);
      		 
      		        mine.add (Calculate7);
      		        Calculate7.setBounds (40, 260, 125, 30);
      		 
      		        mine.add (Calculate15);
      		        Calculate15.setBounds (180, 260, 125, 30);
      		 
      		        mine.add (Calculate30);
      		        Calculate30.setBounds (320, 260, 125, 30);
      		 
      		        mine.add (Payment);
      		        Payment.setBounds (130, 300, 100, 25);
      		 
      		        mine.add (fieldPayment);
      		        fieldPayment.setBounds (240, 300, 100, 25);
      		        fieldPayment.setEditable (false);
      		 
      		        mine.add (AmortizationTable);
      		        AmortizationTable.setBounds (180, 330, 300, 25);
      		 	 		        	 
      		         mine.add (scrollPane);
      		         scrollPane.setBounds (50, 350, 380, 260);
      		         areaAmortTable.setEditable(false);
      		 
      		         mine.add (Clear);
      		         Clear.setBounds (110, 620, 125, 30);
      		 
      	            mine.add (Exit);
      		        Exit.setBounds (250, 620, 125, 30);
      		 
      		        this.setContentPane(mine);
      		        this.pack();
      		        this.setTitle("Mortgage Amortization Calculator");
      		 
      		        setScreenSize(Toolkit.getDefaultToolkit().getScreenSize());
      		        setSize(500, 700);
      		    }
      		    public double loanAmount ()
      		    {
      		        double loanAmount = Double.parseDouble(fieldLoanAmount.getText());
      		        return loanAmount;
      		    }
      		    
      		    public double Interest ()
      		    {
      		        double Interest = Double.parseDouble(fieldInterest.getText());
      		        return Interest;
      		    }
      		    
      		    public double Duration ()
      		    {
      		        double Duration = Double.parseDouble(fieldDuration.getText());
      		        return Duration;
      		    }
      		    
      			public DecimalFormat getDecimalPlaces() {
      				return decimalPlaces;
      			}
      
      			public void setDecimalPlaces(DecimalFormat decimalPlaces) {
      				this.decimalPlaces = decimalPlaces;
      			}
      
      			public DecimalFormat getDecimalPlaces2() {
      				return decimalPlaces2;
      			}
      
      			public void setDecimalPlaces2(DecimalFormat decimalPlaces2) {
      				this.decimalPlaces2 = decimalPlaces2;
      			}
      			
      			public DecimalFormat getDecimalPlaces4() {
      				return decimalPlaces4;
      			}
      
      			public void setDecimalPlaces4(DecimalFormat decimalPlaces4) {
      				this.decimalPlaces4 = decimalPlaces4;
      			}
      
      			public Dimension getScreenSize() {
      				return screenSize;
      			}
      
      			public void setScreenSize(Dimension screenSize) {
      				this.screenSize = screenSize;
      			}
      
      			public DecimalFormat getDecimalPlaces3() {
      				return decimalPlaces3;
      			}
      
      			public void setDecimalPlaces3(DecimalFormat decimalPlaces3) {
      				this.decimalPlaces3 = decimalPlaces3;
      			}
      		}
      // end of program

      Comment

      • neeraj0708
        New Member
        • Feb 2012
        • 21

        #4
        Your Problemhas been solved

        Hi Eric
        In your code you have'nt write the code for amount and intrest, you need to get values for these to field and pass in calculate method.


        Inter= Double.parseDou ble(fieldIntere st.getText());
        Months= Integer.parseIn t(fieldDuration .getText());
        you can run this code. your program will work fine

        import java.awt.*;
        import java.awt.event. *;
        import javax.swing.*;
        import java.text.Decim alFormat;
        import java.text.Numbe rFormat;
        public class MortgageCalcula torWeek3 {

        public static void main(String[] args) { // GUI JFrame Functions for Visibility and exit tool bar.
        JFrame window = new Calculator ();
        window.setDefau ltCloseOperatio n(JFrame.EXIT_O N_CLOSE);
        window.setVisib le(true);
        }
        }
        class Calculator extends JFrame implements ActionListener{ // Shows that the class Calculator extends the JFrame.

        private static final long serialVersionUI D = 1L; // Added to get rid of an error
        private JButton Calculate, Calculate7, Calculate15, Calculate30, Clear, Exit; // Declares the buttons
        private JLabel Payment, Principle, labelTitle, labelInstructio ns,Amortization Table, Interest, Duration, LabelOr; // declares the JLables
        private JTextField fieldPayment, fieldLoanAmount , fieldInterest, fieldDuration; // Declares the JTextfields
        private JTextArea areaAmortTable; // Declares the Amortization table text area. The area supports more lines than the JTextfield.

        //Declare variables and the loan array and assigns values.
        double InterestPaid,Pr inciplePaid,Bal ance,monthlyPay ,loanAmount;
        int[] loanTerm = {7,15,30}; // Declares Loan terms
        double[] intRate = {5.35,5.50,5.75 }; // Declares interest rates
        double loanAmt = loanAmount; // Declares area for user input for principle amount.
        private DecimalFormat decimalPlaces; // sets decimal places for first calculate button
        private DecimalFormat decimalPlaces2; // sets decimal places for second calculate button.
        private DecimalFormat decimalPlaces3; // sets decimal places for third calculate button.
        private DecimalFormat decimalPlaces4;
        private Dimension screenSize; // sets screen size.
        int Months;
        double Inter;


        public void actionPerformed (ActionEvent e)
        {
        //Provides looping functions for the buttons pressed.
        if ("Calculate".eq uals(e.getActio nCommand()))
        {
        setDecimalPlace s4(new DecimalFormat(" 0.00"));
        NumberFormat currency = NumberFormat.ge tCurrencyInstan ce();
        double paymentAmount = Calculate();


        fieldPayment.se tText("" + (currency.forma t(paymentAmount )));
        areaAmortTable. append ("Payment \t Balance After Payment \t Interest Paid\n");

        loanAmt = Double.parseDou ble(fieldLoanAm ount.getText()) ;
        for (int x = 1; x <=(Inter*12); x++){
        Balance=loanAmt ;
        InterestPaid=(( (Inter/100.0)/12.0)*Balance);
        PrinciplePaid=( paymentAmount-InterestPaid);
        loanAmt=(Balanc e-PrinciplePaid);
        areaAmortTable. append (x + " \t " + currency.format (loanAmt) + " \t\t " + currency.format (InterestPaid)+ "\n");
        }
        if (Balance <= 0) //ending statement, balance at $0.00
        areaAmortTable. append ("\tRemainin g balance = $0.00");
        }
        {
        }

        if ("Calculate7".e quals(e.getActi onCommand()))
        {
        setDecimalPlace s(new DecimalFormat(" 0.00"));
        NumberFormat currency = NumberFormat.ge tCurrencyInstan ce();
        double paymentAmount = CalculatePaymen t7();

        fieldPayment.se tText("" + (currency.forma t(paymentAmount )));
        areaAmortTable. append ("Payment \t Balance After Payment \t Interest Paid\n"); // sets fields for loan amortization table

        loanAmt = Double.parseDou ble(fieldLoanAm ount.getText()) ; // allows user to input principle amount.
        for (int x = 1; x <=(loanTerm[0]*12); x++) //Loop through all monthly payments for each loan
        {
        Balance=loanAmt ; //Set Balance to Loan Amount

        //Calculations on monthly payment
        InterestPaid=(( (intRate[0]/100.0)/12.0)*Balance); //Monthly Interest paid
        PrinciplePaid=( paymentAmount-InterestPaid); //Applied towards principle
        loanAmt=(Balanc e-PrinciplePaid); //loan balance after payment

        areaAmortTable. append (x + " \t " + currency.format (loanAmt) + " \t\t " + currency.format (InterestPaid)+ "\n");
        }

        if (Balance <= 0) //ending statement, balance at $0.00
        {
        areaAmortTable. append ("\tRemainin g balance = $0.00");
        }
        }
        else if ("Calculate15". equals(e.getAct ionCommand())) // tells the first button what actions to perform.
        {
        setDecimalPlace s2(new DecimalFormat(" 0.00"));
        NumberFormat currency = NumberFormat.ge tCurrencyInstan ce();
        double paymentAmount = CalculatePaymen t15 ();
        fieldPayment.se tText("" + (currency.forma t(paymentAmount )));

        areaAmortTable. append ("Payment \t Balance After Payment \t Interest Paid\n");
        loanAmt = Double.parseDou ble(fieldLoanAm ount.getText()) ;
        for (int x = 1; x <=(loanTerm[1]*12); x++)
        {
        Balance = loanAmt;
        //Calculations on monthly payment
        InterestPaid=(( intRate[1]/100/12)*Balance); //Monthly Interest paid
        PrinciplePaid=( paymentAmount-InterestPaid); //Applied towards principle
        loanAmt=((Balan ce-PrinciplePaid)) ; //loan balance after payment
        areaAmortTable. append (x + " \t " + currency.format (loanAmt) + " \t\t " + currency.format (InterestPaid)+ "\n");
        }
        if (loanAmt <= 0) //ending statement, balance at $0.00
        {
        areaAmortTable. append ("\tRemainin g balance = $0.00");
        }
        }
        else if ("Calculate30". equals(e.getAct ionCommand()))
        {
        setDecimalPlace s3(new DecimalFormat(" 0.00"));
        NumberFormat currency = NumberFormat.ge tCurrencyInstan ce();
        double paymentAmount = CalculatePaymen t30 ();
        fieldPayment.se tText("" + (currency.forma t(paymentAmount )));
        areaAmortTable. append ("Payment \t Balance After Payment \t Interest Paid\n");
        loanAmt = Double.parseDou ble(fieldLoanAm ount.getText()) ;

        for (int x = 1; x <=(loanTerm[2]*12); x++)
        {
        Balance = loanAmt;
        //Calculations on monthly payment
        InterestPaid=(( intRate[2]/100/12)*Balance); //Monthly Interest paid
        PrinciplePaid=( paymentAmount-InterestPaid); //Applied towards principle
        loanAmt=((Balan ce-PrinciplePaid)) ; //loan balance after payment
        areaAmortTable. append (x + " \t " + currency.format (loanAmt) + " \t\t " + currency.format (InterestPaid)+ "\n");
        }
        if (loanAmt <= 0) //ending statement, balance at $0.00
        {
        areaAmortTable. append ("\tRemainin g balance = $0.00");

        }
        }

        else if ("Clear".equals (e.getActionCom mand()))
        {
        ClearFields ();
        }

        else
        {
        //System.exit(0); //End and close application.
        }
        }

        public double CalculatePaymen t7 ()
        {

        try //Check for number entry
        {
        //Perform payment calculations if input is valid

        fieldPayment.se tText ("");
        double Payment =(loanAmount() * (intRate[0]/100/12)) / (1 - Math.pow(1/(1 + (intRate[0]/100/12)),loanTerm[0]*12));
        return Payment;
        }

        catch (NumberFormatEx ception event)
        {
        //Display error message for invalid characters and beep at user.
        // beeps when there is an error
        JOptionPane.sho wMessageDialog( null, " Invalid entry, please enter numbers only", "ERROR", JOptionPane.ERR OR_MESSAGE);
        System.out.prin t ( "\007" );
        return 0;
        }
        }

        public double CalculatePaymen t15 ()
        {

        try //Check for valid numeric input
        {
        //Display error message for invalid characters and beep at user.
        fieldPayment.se tText ("");
        double Payment =(loanAmount() * (intRate[1]/100/12)) / (1 - Math.pow(1/(1 + (intRate[1]/100/12)),loanTerm[1]*12));
        return Payment;
        }

        catch (NumberFormatEx ception event)
        {
        // Display error message for invalid characters and beep at user.
        System.out.prin t ( "\007" ); // beeps when there is an error
        JOptionPane.sho wMessageDialog( null, " Invalid entry, please enter numbers only", "ERROR", JOptionPane.ERR OR_MESSAGE);
        return 0;
        }
        }

        public double CalculatePaymen t30 ()
        {
        //Check for valid numeric input
        try
        {
        //Perform payment calculations if input is valid
        fieldPayment.se tText ("");
        double Payment =(loanAmount() * (intRate[2]/100/12)) / (1 - Math.pow(1/(1 + (intRate[2]/100/12)),loanTerm[2]*12));
        return Payment;
        }

        catch (NumberFormatEx ception event)
        {
        // Display error message for invalid characters and beep at user.
        System.out.prin t ( "\007" ); // beeps when there is an error
        JOptionPane.sho wMessageDialog( null, " Invalid entry, please enter numbers only", "Error", JOptionPane.ERR OR_MESSAGE);
        return 0;
        }

        }
        public double Calculate(){
        try{

        fieldPayment.se tText("");
        //Modified by neeraj *************** ***********//////////
        Inter= Double.parseDou ble(fieldIntere st.getText());
        Months= Integer.parseIn t(fieldDuration .getText());
        //Modified by neeraj *************** ***********//////////
        double Payment =(loanAmount() * (Inter/100/12)) / (1 - Math.pow(1/(1 + (Inter/100/12)),Months*12) );
        return Payment;

        }

        catch (NumberFormatEx ception event){
        JOptionPane.sho wMessageDialog( null, "Invalid entry, please enter numbers only", "Error", JOptionPane.ERR OR_MESSAGE);
        return 0;
        }
        }


        public void ClearFields ()
        {
        //clears all fields for new input.
        fieldPayment.se tText ("");
        fieldLoanAmount .setText ("");
        areaAmortTable. setText ("");
        fieldInterest.s etText ("");
        fieldDuration.s etText ("");

        }

        public Calculator ()
        {
        //Sets up buttons for GUI
        Calculate = new JButton ("Calculate" );
        Calculate.setAc tionCommand ("Calculate" );
        Calculate7 = new JButton ("7 Year, 5.35%");
        Calculate7.setA ctionCommand ("Calculate7 ");
        Calculate15 = new JButton ("15 Year, 5.50%");
        Calculate15.set ActionCommand ("Calculate15") ;
        Calculate30 = new JButton ("30 Year, 5.75%");
        Calculate30.set ActionCommand ("Calculate30") ;
        Clear = new JButton ("Clear ");
        Clear.setAction Command ("Clear");
        Exit = new JButton ("Exit");
        Exit.setActionC ommand ("Exit");

        //Set up labels and field sizes for GUI
        labelTitle = new JLabel ("Mortgage Amortization Calculator");
        labelInstructio ns = new JLabel ("Enter the Principle, Interest rate, and Loan Duration.");
        LabelOr = new JLabel (" Or Pick From These Loan Options After Entering Loan Amount");
        Payment = new JLabel ("Monthly Payment:");
        Principle = new JLabel ("Amount of Loan:");
        fieldPayment = new JTextField ("", 12);
        fieldLoanAmount = new JTextField ("", 10);
        AmortizationTab le = new JLabel ("Amortizati on Table");
        areaAmortTable = new JTextArea (10, 300);
        Interest = new JLabel ("Interest Rate:");
        Duration = new JLabel ("Duration:" );
        fieldInterest = new JTextField ("", 12);
        fieldDuration = new JTextField ("", 10);

        JScrollPane scrollPane = new JScrollPane (areaAmortTable , JScrollPane.VER TICAL_SCROLLBAR _ALWAYS,
        JScrollPane.HOR IZONTAL_SCROLLB AR_ALWAYS);

        //Set up listeners for each button.
        Calculate.addAc tionListener(th is);
        Calculate7.addA ctionListener(t his);
        Calculate15.add ActionListener( this);
        Calculate30.add ActionListener( this);
        Clear.addAction Listener(this);
        Exit.addActionL istener(this);

        //Constructs GUI.
        JPanel mine = new JPanel();
        mine.setLayout (null);

        mine.add (labelTitle);
        labelTitle.setB ounds (110, 30, 700, 15);

        mine.add (labelInstructi ons);
        labelInstructio ns.setBounds (80, 70, 450, 15);

        mine.add (Principle);
        Principle.setBo unds (130, 110, 100, 25);

        mine.add(Intere st);
        Interest.setBou nds (130 , 140, 120, 25);

        mine.add(Calcul ate);
        Calculate.setBo unds(350, 145, 115, 25);

        mine.add(Durati on);
        Duration.setBou nds(130, 170, 120, 25);

        mine.add (fieldLoanAmoun t);
        fieldLoanAmount .setBounds (240, 110, 100, 25);

        mine.add(fieldI nterest);
        fieldInterest.s etBounds (240, 140, 100, 25);

        mine.add(fieldD uration);
        fieldDuration.s etBounds (240, 170, 100, 25);

        mine.add(LabelO r);
        LabelOr.setBoun ds(80, 220, 400, 25);

        mine.add (Calculate7);
        Calculate7.setB ounds (40, 260, 125, 30);

        mine.add (Calculate15);
        Calculate15.set Bounds (180, 260, 125, 30);

        mine.add (Calculate30);
        Calculate30.set Bounds (320, 260, 125, 30);

        mine.add (Payment);
        Payment.setBoun ds (130, 300, 100, 25);

        mine.add (fieldPayment);
        fieldPayment.se tBounds (240, 300, 100, 25);
        fieldPayment.se tEditable (false);

        mine.add (AmortizationTa ble);
        AmortizationTab le.setBounds (180, 330, 300, 25);

        mine.add (scrollPane);
        scrollPane.setB ounds (50, 350, 380, 260);
        areaAmortTable. setEditable(fal se);

        mine.add (Clear);
        Clear.setBounds (110, 620, 125, 30);

        mine.add (Exit);
        Exit.setBounds (250, 620, 125, 30);

        this.setContent Pane(mine);
        this.pack();
        this.setTitle(" Mortgage Amortization Calculator");

        setScreenSize(T oolkit.getDefau ltToolkit().get ScreenSize());
        setSize(500, 700);
        }
        public double loanAmount ()
        {
        double loanAmount = Double.parseDou ble(fieldLoanAm ount.getText()) ;
        System.out.prin tln("loanAmount = "+loanAmoun t+" fieldLoanAmount .getText()= "+fieldLoanAmou nt.getText());
        return loanAmount;
        }

        public DecimalFormat getDecimalPlace s() {
        return decimalPlaces;
        }

        public void setDecimalPlace s(DecimalFormat decimalPlaces) {
        this.decimalPla ces = decimalPlaces;
        }

        public DecimalFormat getDecimalPlace s2() {
        return decimalPlaces2;
        }

        public void setDecimalPlace s2(DecimalForma t decimalPlaces2) {
        this.decimalPla ces2 = decimalPlaces2;
        }

        public DecimalFormat getDecimalPlace s4() {
        return decimalPlaces4;
        }

        public void setDecimalPlace s4(DecimalForma t decimalPlaces4) {
        this.decimalPla ces4 = decimalPlaces4;
        }

        public Dimension getScreenSize() {
        return screenSize;
        }

        public void setScreenSize(D imension screenSize) {
        this.screenSize = screenSize;
        }

        public DecimalFormat getDecimalPlace s3() {
        return decimalPlaces3;
        }

        public void setDecimalPlace s3(DecimalForma t decimalPlaces3) {
        this.decimalPla ces3 = decimalPlaces3;
        }
        }
        // end of program


        And i hv some suggestion for your program.
        " specify the duration as month or year" I think It is taking as a year so kindly check your code again.

        Please run the code and tell me is it working fine or not.

        Comment

        • neeraj0708
          New Member
          • Feb 2012
          • 21

          #5
          Your Problemhas been solved

          Hi Eric
          In your code you have'nt write the code for amount and intrest, you need to get values for these to field and pass in calculate method.
          Inter= Double.parseDou ble(fieldIntere st.getText());
          Months= Integer.parseIn t(fieldDuration .getText());
          you can run this code. your program will work fine

          import java.awt.*;
          import java.awt.event. *;
          import javax.swing.*;
          import java.text.Decim alFormat;
          import java.text.Numbe rFormat;
          public class MortgageCalcula torWeek3 {

          public static void main(String[] args) { // GUI JFrame Functions for Visibility and exit tool bar.
          JFrame window = new Calculator ();
          window.setDefau ltCloseOperatio n(JFrame.EXIT_O N_CLOSE);
          window.setVisib le(true);
          }
          }
          class Calculator extends JFrame implements ActionListener{ // Shows that the class Calculator extends the JFrame.

          private static final long serialVersionUI D = 1L; // Added to get rid of an error
          private JButton Calculate, Calculate7, Calculate15, Calculate30, Clear, Exit; // Declares the buttons
          private JLabel Payment, Principle, labelTitle, labelInstructio ns,Amortization Table, Interest, Duration, LabelOr; // declares the JLables
          private JTextField fieldPayment, fieldLoanAmount , fieldInterest, fieldDuration; // Declares the JTextfields
          private JTextArea areaAmortTable; // Declares the Amortization table text area. The area supports more lines than the JTextfield.

          //Declare variables and the loan array and assigns values.
          double InterestPaid,Pr inciplePaid,Bal ance,monthlyPay ,loanAmount;
          int[] loanTerm = {7,15,30}; // Declares Loan terms
          double[] intRate = {5.35,5.50,5.75 }; // Declares interest rates
          double loanAmt = loanAmount; // Declares area for user input for principle amount.
          private DecimalFormat decimalPlaces; // sets decimal places for first calculate button
          private DecimalFormat decimalPlaces2; // sets decimal places for second calculate button.
          private DecimalFormat decimalPlaces3; // sets decimal places for third calculate button.
          private DecimalFormat decimalPlaces4;
          private Dimension screenSize; // sets screen size.
          int Months;
          double Inter;


          public void actionPerformed (ActionEvent e)
          {
          //Provides looping functions for the buttons pressed.
          if ("Calculate".eq uals(e.getActio nCommand()))
          {
          setDecimalPlace s4(new DecimalFormat(" 0.00"));
          NumberFormat currency = NumberFormat.ge tCurrencyInstan ce();
          double paymentAmount = Calculate();


          fieldPayment.se tText("" + (currency.forma t(paymentAmount )));
          areaAmortTable. append ("Payment \t Balance After Payment \t Interest Paid\n");

          loanAmt = Double.parseDou ble(fieldLoanAm ount.getText()) ;
          for (int x = 1; x <=(Inter*12); x++){
          Balance=loanAmt ;
          InterestPaid=(( (Inter/100.0)/12.0)*Balance);
          PrinciplePaid=( paymentAmount-InterestPaid);
          loanAmt=(Balanc e-PrinciplePaid);
          areaAmortTable. append (x + " \t " + currency.format (loanAmt) + " \t\t " + currency.format (InterestPaid)+ "\n");
          }
          if (Balance <= 0) //ending statement, balance at $0.00
          areaAmortTable. append ("\tRemainin g balance = $0.00");
          }
          {
          }

          if ("Calculate7".e quals(e.getActi onCommand()))
          {
          setDecimalPlace s(new DecimalFormat(" 0.00"));
          NumberFormat currency = NumberFormat.ge tCurrencyInstan ce();
          double paymentAmount = CalculatePaymen t7();

          fieldPayment.se tText("" + (currency.forma t(paymentAmount )));
          areaAmortTable. append ("Payment \t Balance After Payment \t Interest Paid\n"); // sets fields for loan amortization table

          loanAmt = Double.parseDou ble(fieldLoanAm ount.getText()) ; // allows user to input principle amount.
          for (int x = 1; x <=(loanTerm[0]*12); x++) //Loop through all monthly payments for each loan
          {
          Balance=loanAmt ; //Set Balance to Loan Amount

          //Calculations on monthly payment
          InterestPaid=(( (intRate[0]/100.0)/12.0)*Balance); //Monthly Interest paid
          PrinciplePaid=( paymentAmount-InterestPaid); //Applied towards principle
          loanAmt=(Balanc e-PrinciplePaid); //loan balance after payment

          areaAmortTable. append (x + " \t " + currency.format (loanAmt) + " \t\t " + currency.format (InterestPaid)+ "\n");
          }

          if (Balance <= 0) //ending statement, balance at $0.00
          {
          areaAmortTable. append ("\tRemainin g balance = $0.00");
          }
          }
          else if ("Calculate15". equals(e.getAct ionCommand())) // tells the first button what actions to perform.
          {
          setDecimalPlace s2(new DecimalFormat(" 0.00"));
          NumberFormat currency = NumberFormat.ge tCurrencyInstan ce();
          double paymentAmount = CalculatePaymen t15 ();
          fieldPayment.se tText("" + (currency.forma t(paymentAmount )));

          areaAmortTable. append ("Payment \t Balance After Payment \t Interest Paid\n");
          loanAmt = Double.parseDou ble(fieldLoanAm ount.getText()) ;
          for (int x = 1; x <=(loanTerm[1]*12); x++)
          {
          Balance = loanAmt;
          //Calculations on monthly payment
          InterestPaid=(( intRate[1]/100/12)*Balance); //Monthly Interest paid
          PrinciplePaid=( paymentAmount-InterestPaid); //Applied towards principle
          loanAmt=((Balan ce-PrinciplePaid)) ; //loan balance after payment
          areaAmortTable. append (x + " \t " + currency.format (loanAmt) + " \t\t " + currency.format (InterestPaid)+ "\n");
          }
          if (loanAmt <= 0) //ending statement, balance at $0.00
          {
          areaAmortTable. append ("\tRemainin g balance = $0.00");
          }
          }
          else if ("Calculate30". equals(e.getAct ionCommand()))
          {
          setDecimalPlace s3(new DecimalFormat(" 0.00"));
          NumberFormat currency = NumberFormat.ge tCurrencyInstan ce();
          double paymentAmount = CalculatePaymen t30 ();
          fieldPayment.se tText("" + (currency.forma t(paymentAmount )));
          areaAmortTable. append ("Payment \t Balance After Payment \t Interest Paid\n");
          loanAmt = Double.parseDou ble(fieldLoanAm ount.getText()) ;

          for (int x = 1; x <=(loanTerm[2]*12); x++)
          {
          Balance = loanAmt;
          //Calculations on monthly payment
          InterestPaid=(( intRate[2]/100/12)*Balance); //Monthly Interest paid
          PrinciplePaid=( paymentAmount-InterestPaid); //Applied towards principle
          loanAmt=((Balan ce-PrinciplePaid)) ; //loan balance after payment
          areaAmortTable. append (x + " \t " + currency.format (loanAmt) + " \t\t " + currency.format (InterestPaid)+ "\n");
          }
          if (loanAmt <= 0) //ending statement, balance at $0.00
          {
          areaAmortTable. append ("\tRemainin g balance = $0.00");

          }
          }

          else if ("Clear".equals (e.getActionCom mand()))
          {
          ClearFields ();
          }

          else
          {
          //System.exit(0); //End and close application.
          }
          }

          public double CalculatePaymen t7 ()
          {

          try //Check for number entry
          {
          //Perform payment calculations if input is valid

          fieldPayment.se tText ("");
          double Payment =(loanAmount() * (intRate[0]/100/12)) / (1 - Math.pow(1/(1 + (intRate[0]/100/12)),loanTerm[0]*12));
          return Payment;
          }

          catch (NumberFormatEx ception event)
          {
          //Display error message for invalid characters and beep at user.
          // beeps when there is an error
          JOptionPane.sho wMessageDialog( null, " Invalid entry, please enter numbers only", "ERROR", JOptionPane.ERR OR_MESSAGE);
          System.out.prin t ( "\007" );
          return 0;
          }
          }

          public double CalculatePaymen t15 ()
          {

          try //Check for valid numeric input
          {
          //Display error message for invalid characters and beep at user.
          fieldPayment.se tText ("");
          double Payment =(loanAmount() * (intRate[1]/100/12)) / (1 - Math.pow(1/(1 + (intRate[1]/100/12)),loanTerm[1]*12));
          return Payment;
          }

          catch (NumberFormatEx ception event)
          {
          // Display error message for invalid characters and beep at user.
          System.out.prin t ( "\007" ); // beeps when there is an error
          JOptionPane.sho wMessageDialog( null, " Invalid entry, please enter numbers only", "ERROR", JOptionPane.ERR OR_MESSAGE);
          return 0;
          }
          }

          public double CalculatePaymen t30 ()
          {
          //Check for valid numeric input
          try
          {
          //Perform payment calculations if input is valid
          fieldPayment.se tText ("");
          double Payment =(loanAmount() * (intRate[2]/100/12)) / (1 - Math.pow(1/(1 + (intRate[2]/100/12)),loanTerm[2]*12));
          return Payment;
          }

          catch (NumberFormatEx ception event)
          {
          // Display error message for invalid characters and beep at user.
          System.out.prin t ( "\007" ); // beeps when there is an error
          JOptionPane.sho wMessageDialog( null, " Invalid entry, please enter numbers only", "Error", JOptionPane.ERR OR_MESSAGE);
          return 0;
          }

          }
          public double Calculate(){
          try{

          fieldPayment.se tText("");
          //Modified by neeraj *************** ***********//////////
          Inter= Double.parseDou ble(fieldIntere st.getText());
          Months= Integer.parseIn t(fieldDuration .getText());
          //Modified by neeraj *************** ***********//////////
          double Payment =(loanAmount() * (Inter/100/12)) / (1 - Math.pow(1/(1 + (Inter/100/12)),Months*12) );
          return Payment;

          }

          catch (NumberFormatEx ception event){
          JOptionPane.sho wMessageDialog( null, "Invalid entry, please enter numbers only", "Error", JOptionPane.ERR OR_MESSAGE);
          return 0;
          }
          }


          public void ClearFields ()
          {
          //clears all fields for new input.
          fieldPayment.se tText ("");
          fieldLoanAmount .setText ("");
          areaAmortTable. setText ("");
          fieldInterest.s etText ("");
          fieldDuration.s etText ("");

          }

          public Calculator ()
          {
          //Sets up buttons for GUI
          Calculate = new JButton ("Calculate" );
          Calculate.setAc tionCommand ("Calculate" );
          Calculate7 = new JButton ("7 Year, 5.35%");
          Calculate7.setA ctionCommand ("Calculate7 ");
          Calculate15 = new JButton ("15 Year, 5.50%");
          Calculate15.set ActionCommand ("Calculate15") ;
          Calculate30 = new JButton ("30 Year, 5.75%");
          Calculate30.set ActionCommand ("Calculate30") ;
          Clear = new JButton ("Clear ");
          Clear.setAction Command ("Clear");
          Exit = new JButton ("Exit");
          Exit.setActionC ommand ("Exit");

          //Set up labels and field sizes for GUI
          labelTitle = new JLabel ("Mortgage Amortization Calculator");
          labelInstructio ns = new JLabel ("Enter the Principle, Interest rate, and Loan Duration.");
          LabelOr = new JLabel (" Or Pick From These Loan Options After Entering Loan Amount");
          Payment = new JLabel ("Monthly Payment:");
          Principle = new JLabel ("Amount of Loan:");
          fieldPayment = new JTextField ("", 12);
          fieldLoanAmount = new JTextField ("", 10);
          AmortizationTab le = new JLabel ("Amortizati on Table");
          areaAmortTable = new JTextArea (10, 300);
          Interest = new JLabel ("Interest Rate:");
          Duration = new JLabel ("Duration:" );
          fieldInterest = new JTextField ("", 12);
          fieldDuration = new JTextField ("", 10);

          JScrollPane scrollPane = new JScrollPane (areaAmortTable , JScrollPane.VER TICAL_SCROLLBAR _ALWAYS,
          JScrollPane.HOR IZONTAL_SCROLLB AR_ALWAYS);

          //Set up listeners for each button.
          Calculate.addAc tionListener(th is);
          Calculate7.addA ctionListener(t his);
          Calculate15.add ActionListener( this);
          Calculate30.add ActionListener( this);
          Clear.addAction Listener(this);
          Exit.addActionL istener(this);

          //Constructs GUI.
          JPanel mine = new JPanel();
          mine.setLayout (null);

          mine.add (labelTitle);
          labelTitle.setB ounds (110, 30, 700, 15);

          mine.add (labelInstructi ons);
          labelInstructio ns.setBounds (80, 70, 450, 15);

          mine.add (Principle);
          Principle.setBo unds (130, 110, 100, 25);

          mine.add(Intere st);
          Interest.setBou nds (130 , 140, 120, 25);

          mine.add(Calcul ate);
          Calculate.setBo unds(350, 145, 115, 25);

          mine.add(Durati on);
          Duration.setBou nds(130, 170, 120, 25);

          mine.add (fieldLoanAmoun t);
          fieldLoanAmount .setBounds (240, 110, 100, 25);

          mine.add(fieldI nterest);
          fieldInterest.s etBounds (240, 140, 100, 25);

          mine.add(fieldD uration);
          fieldDuration.s etBounds (240, 170, 100, 25);

          mine.add(LabelO r);
          LabelOr.setBoun ds(80, 220, 400, 25);

          mine.add (Calculate7);
          Calculate7.setB ounds (40, 260, 125, 30);

          mine.add (Calculate15);
          Calculate15.set Bounds (180, 260, 125, 30);

          mine.add (Calculate30);
          Calculate30.set Bounds (320, 260, 125, 30);

          mine.add (Payment);
          Payment.setBoun ds (130, 300, 100, 25);

          mine.add (fieldPayment);
          fieldPayment.se tBounds (240, 300, 100, 25);
          fieldPayment.se tEditable (false);

          mine.add (AmortizationTa ble);
          AmortizationTab le.setBounds (180, 330, 300, 25);

          mine.add (scrollPane);
          scrollPane.setB ounds (50, 350, 380, 260);
          areaAmortTable. setEditable(fal se);

          mine.add (Clear);
          Clear.setBounds (110, 620, 125, 30);

          mine.add (Exit);
          Exit.setBounds (250, 620, 125, 30);

          this.setContent Pane(mine);
          this.pack();
          this.setTitle(" Mortgage Amortization Calculator");

          setScreenSize(T oolkit.getDefau ltToolkit().get ScreenSize());
          setSize(500, 700);
          }
          public double loanAmount ()
          {
          double loanAmount = Double.parseDou ble(fieldLoanAm ount.getText()) ;
          System.out.prin tln("loanAmount = "+loanAmoun t+" fieldLoanAmount .getText()= "+fieldLoanAmou nt.getText());
          return loanAmount;
          }

          public DecimalFormat getDecimalPlace s() {
          return decimalPlaces;
          }

          public void setDecimalPlace s(DecimalFormat decimalPlaces) {
          this.decimalPla ces = decimalPlaces;
          }

          public DecimalFormat getDecimalPlace s2() {
          return decimalPlaces2;
          }

          public void setDecimalPlace s2(DecimalForma t decimalPlaces2) {
          this.decimalPla ces2 = decimalPlaces2;
          }

          public DecimalFormat getDecimalPlace s4() {
          return decimalPlaces4;
          }

          public void setDecimalPlace s4(DecimalForma t decimalPlaces4) {
          this.decimalPla ces4 = decimalPlaces4;
          }

          public Dimension getScreenSize() {
          return screenSize;
          }

          public void setScreenSize(D imension screenSize) {
          this.screenSize = screenSize;
          }

          public DecimalFormat getDecimalPlace s3() {
          return decimalPlaces3;
          }

          public void setDecimalPlace s3(DecimalForma t decimalPlaces3) {
          this.decimalPla ces3 = decimalPlaces3;
          }
          }
          // end of program


          Comment

          • Eric Miles
            New Member
            • Feb 2012
            • 5

            #6
            I changed the code that you specified, but the program still terminates when you press the calculate button. I see where I forget to put in those variables, but there are still problems with the exit over-ride.

            Comment

            • neeraj0708
              New Member
              • Feb 2012
              • 21

              #7
              Hi Eric,

              Try this It is working fine.


              Code:
              import java.awt.*; 
              import java.awt.event.*; 
              import javax.swing.*; 
              import java.text.DecimalFormat; 
              import java.text.NumberFormat; 
              public class MortgageCalculatorWeek3 { 
              
              public static void main(String[] args) { // GUI JFrame Functions for Visibility and exit tool bar. 
              JFrame window = new Calculator (); 
              window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
              window.setVisible(true); 
              } 
              } 
              class Calculator extends JFrame implements ActionListener{ // Shows that the class Calculator extends the JFrame. 
              
              private static final long serialVersionUID = 1L; // Added to get rid of an error 
              private JButton Calculate, Calculate7, Calculate15, Calculate30, Clear, Exit; // Declares the buttons 
              private JLabel Payment, Principle, labelTitle, labelInstructions,AmortizationTable, Interest, Duration, LabelOr; // declares the JLables 
              private JTextField fieldPayment, fieldLoanAmount, fieldInterest, fieldDuration; // Declares the JTextfields 
              private JTextArea areaAmortTable; // Declares the Amortization table text area. The area supports more lines than the JTextfield. 
              
              //Declare variables and the loan array and assigns values. 
              double InterestPaid,PrinciplePaid,Balance,monthlyPay,loanAmount; 
              int[] loanTerm = {7,15,30}; // Declares Loan terms 
              double[] intRate = {5.35,5.50,5.75}; // Declares interest rates 
              double loanAmt = loanAmount; // Declares area for user input for principle amount. 
              private DecimalFormat decimalPlaces; // sets decimal places for first calculate button 
              private DecimalFormat decimalPlaces2; // sets decimal places for second calculate button. 
              private DecimalFormat decimalPlaces3; // sets decimal places for third calculate button. 
              private DecimalFormat decimalPlaces4; 
              private Dimension screenSize; // sets screen size. 
              int Months; 
              double Inter; 
              
              
              public void actionPerformed (ActionEvent e) 
              { 
              //Provides looping functions for the buttons pressed. 
              if ("Calculate".equals(e.getActionCommand())) 
              {
              
              setDecimalPlaces4(new DecimalFormat("0.00")); 
              NumberFormat currency = NumberFormat.getCurrencyInstance(); 
              double paymentAmount = Calculate(); 
              
              
              fieldPayment.setText("" + (currency.format(paymentAmount))); 
              areaAmortTable.append ("Payment \t Balance After Payment \t Interest Paid\n"); 
              
              loanAmt = Double.parseDouble(fieldLoanAmount.getText()); 
              for (int x = 1; x <=(Inter*12); x++){ 
              Balance=loanAmt; 
              InterestPaid=(((Inter/100.0)/12.0)*Balance); 
              PrinciplePaid=(paymentAmount-InterestPaid); 
              loanAmt=(Balance-PrinciplePaid); 
              areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n"); 
              } 
              if (Balance <= 0) //ending statement, balance at $0.00 
              areaAmortTable.append ("\tRemaining balance = $0.00"); 
              }
              else if ("Calculate7".equals(e.getActionCommand())) 
              { 
              setDecimalPlaces(new DecimalFormat("0.00")); 
              NumberFormat currency = NumberFormat.getCurrencyInstance(); 
              double paymentAmount = CalculatePayment7(); 
              
              fieldPayment.setText("" + (currency.format(paymentAmount))); 
              areaAmortTable.append ("Payment \t Balance After Payment \t Interest Paid\n"); // sets fields for loan amortization table 
              
              loanAmt = Double.parseDouble(fieldLoanAmount.getText()); // allows user to input principle amount. 
              for (int x = 1; x <=(loanTerm[0]*12); x++) //Loop through all monthly payments for each loan 
              { 
              Balance=loanAmt; //Set Balance to Loan Amount 
              
              //Calculations on monthly payment 
              InterestPaid=(((intRate[0]/100.0)/12.0)*Balance); //Monthly Interest paid 
              PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle 
              loanAmt=(Balance-PrinciplePaid); //loan balance after payment 
              
              areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n"); 
              } 
              
              if (Balance <= 0) //ending statement, balance at $0.00 
              { 
              areaAmortTable.append ("\tRemaining balance = $0.00"); 
              } 
              } 
              else if ("Calculate15".equals(e.getActionCommand())) // tells the first button what actions to perform. 
              { 
              setDecimalPlaces2(new DecimalFormat("0.00")); 
              NumberFormat currency = NumberFormat.getCurrencyInstance(); 
              double paymentAmount = CalculatePayment15 (); 
              fieldPayment.setText("" + (currency.format(paymentAmount))); 
              
              areaAmortTable.append ("Payment \t Balance After Payment \t Interest Paid\n"); 
              loanAmt = Double.parseDouble(fieldLoanAmount.getText()); 
              for (int x = 1; x <=(loanTerm[1]*12); x++) 
              { 
              Balance = loanAmt; 
              //Calculations on monthly payment 
              InterestPaid=((intRate[1]/100/12)*Balance); //Monthly Interest paid 
              PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle 
              loanAmt=((Balance-PrinciplePaid)); //loan balance after payment 
              areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n"); 
              } 
              if (loanAmt <= 0) //ending statement, balance at $0.00 
              { 
              areaAmortTable.append ("\tRemaining balance = $0.00"); 
              } 
              } 
              else if ("Calculate30".equals(e.getActionCommand())) 
              { 
              setDecimalPlaces3(new DecimalFormat("0.00")); 
              NumberFormat currency = NumberFormat.getCurrencyInstance(); 
              double paymentAmount = CalculatePayment30 (); 
              fieldPayment.setText("" + (currency.format(paymentAmount))); 
              areaAmortTable.append ("Payment \t Balance After Payment \t Interest Paid\n"); 
              loanAmt = Double.parseDouble(fieldLoanAmount.getText()); 
              
              for (int x = 1; x <=(loanTerm[2]*12); x++) 
              { 
              Balance = loanAmt; 
              //Calculations on monthly payment 
              InterestPaid=((intRate[2]/100/12)*Balance); //Monthly Interest paid 
              PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle 
              loanAmt=((Balance-PrinciplePaid)); //loan balance after payment 
              areaAmortTable.append (x + " \t " + currency.format(loanAmt) + " \t\t " + currency.format(InterestPaid)+"\n"); 
              } 
              if (loanAmt <= 0) //ending statement, balance at $0.00 
              { 
              areaAmortTable.append ("\tRemaining balance = $0.00"); 
              
              } 
              } 
              
              else if ("Clear".equals(e.getActionCommand())) 
              { 
              ClearFields (); 
              } 
              
              else 
              { 
              System.exit(0); //End and close application. 
              } 
              } 
              
              public double CalculatePayment7 () 
              { 
              
              try //Check for number entry 
              { 
              //Perform payment calculations if input is valid 
              
              fieldPayment.setText (""); 
              double Payment =(loanAmount() * (intRate[0]/100/12)) / (1 - Math.pow(1/(1 + (intRate[0]/100/12)),loanTerm[0]*12)); 
              return Payment; 
              } 
              
              catch (NumberFormatException event) 
              { 
              //Display error message for invalid characters and beep at user. 
              // beeps when there is an error 
              JOptionPane.showMessageDialog(null, " Invalid entry, please enter numbers only", "ERROR", JOptionPane.ERROR_MESSAGE); 
              System.out.print ( "\007" ); 
              return 0; 
              } 
              } 
              
              public double CalculatePayment15 () 
              { 
              
              try //Check for valid numeric input 
              { 
              //Display error message for invalid characters and beep at user. 
              fieldPayment.setText (""); 
              double Payment =(loanAmount() * (intRate[1]/100/12)) / (1 - Math.pow(1/(1 + (intRate[1]/100/12)),loanTerm[1]*12)); 
              return Payment; 
              } 
              
              catch (NumberFormatException event) 
              { 
              // Display error message for invalid characters and beep at user. 
              System.out.print ( "\007" ); // beeps when there is an error 
              JOptionPane.showMessageDialog(null, " Invalid entry, please enter numbers only", "ERROR", JOptionPane.ERROR_MESSAGE); 
              return 0; 
              } 
              } 
              
              public double CalculatePayment30 () 
              { 
              //Check for valid numeric input 
              try 
              { 
              //Perform payment calculations if input is valid 
              fieldPayment.setText (""); 
              double Payment =(loanAmount() * (intRate[2]/100/12)) / (1 - Math.pow(1/(1 + (intRate[2]/100/12)),loanTerm[2]*12)); 
              return Payment; 
              } 
              
              catch (NumberFormatException event) 
              { 
              // Display error message for invalid characters and beep at user. 
              System.out.print ( "\007" ); // beeps when there is an error 
              JOptionPane.showMessageDialog(null, " Invalid entry, please enter numbers only", "Error", JOptionPane.ERROR_MESSAGE); 
              return 0; 
              } 
              
              } 
              public double Calculate(){ 
              try{ 
              
              fieldPayment.setText(""); 
              //Modified by neeraj **************************//////////
              Inter= Double.parseDouble(fieldInterest.getText()); 
              Months= Integer.parseInt(fieldDuration.getText()); 
              //Modified by neeraj **************************//////////
              double Payment =(loanAmount() * (Inter/100/12)) / (1 - Math.pow(1/(1 + (Inter/100/12)),Months*12)); 
              return Payment; 
              
              } 
              
              catch (NumberFormatException event){ 
              JOptionPane.showMessageDialog(null, "Invalid entry, please enter numbers only", "Error", JOptionPane.ERROR_MESSAGE); 
              return 0; 
              } 
              } 
              
              
              public void ClearFields () 
              { 
              //clears all fields for new input. 
              fieldPayment.setText (""); 
              fieldLoanAmount.setText (""); 
              areaAmortTable.setText (""); 
              fieldInterest.setText (""); 
              fieldDuration.setText (""); 
              
              } 
              
              public Calculator () 
              { 
              //Sets up buttons for GUI 
              Calculate = new JButton ("Calculate"); 
              Calculate.setActionCommand ("Calculate"); 
              Calculate7 = new JButton ("7 Year, 5.35%"); 
              Calculate7.setActionCommand ("Calculate7"); 
              Calculate15 = new JButton ("15 Year, 5.50%"); 
              Calculate15.setActionCommand ("Calculate15"); 
              Calculate30 = new JButton ("30 Year, 5.75%"); 
              Calculate30.setActionCommand ("Calculate30"); 
              Clear = new JButton ("Clear "); 
              Clear.setActionCommand ("Clear"); 
              Exit = new JButton ("Exit"); 
              Exit.setActionCommand ("Exit"); 
              
              //Set up labels and field sizes for GUI 
              labelTitle = new JLabel ("Mortgage Amortization Calculator"); 
              labelInstructions = new JLabel ("Enter the Principle, Interest rate, and Loan Duration."); 
              LabelOr = new JLabel (" Or Pick From These Loan Options After Entering Loan Amount"); 
              Payment = new JLabel ("Monthly Payment:"); 
              Principle = new JLabel ("Amount of Loan:"); 
              fieldPayment = new JTextField ("", 12); 
              fieldLoanAmount = new JTextField ("", 10); 
              AmortizationTable = new JLabel ("Amortization Table"); 
              areaAmortTable = new JTextArea (10, 300); 
              Interest = new JLabel ("Interest Rate:"); 
              Duration = new JLabel ("Duration:"); 
              fieldInterest = new JTextField ("", 12); 
              fieldDuration = new JTextField ("", 10); 
              
              JScrollPane scrollPane = new JScrollPane (areaAmortTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
              JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 
              
              //Set up listeners for each button. 
              Calculate.addActionListener(this); 
              Calculate7.addActionListener(this); 
              Calculate15.addActionListener(this); 
              Calculate30.addActionListener(this); 
              Clear.addActionListener(this); 
              Exit.addActionListener(this); 
              
              //Constructs GUI. 
              JPanel mine = new JPanel(); 
              mine.setLayout (null); 
              
              mine.add (labelTitle); 
              labelTitle.setBounds (110, 30, 700, 15); 
              
              mine.add (labelInstructions); 
              labelInstructions.setBounds (80, 70, 450, 15); 
              
              mine.add (Principle); 
              Principle.setBounds (130, 110, 100, 25); 
              
              mine.add(Interest); 
              Interest.setBounds (130 , 140, 120, 25); 
              
              mine.add(Calculate); 
              Calculate.setBounds(350, 145, 115, 25); 
              
              mine.add(Duration); 
              Duration.setBounds(130, 170, 120, 25); 
              
              mine.add (fieldLoanAmount); 
              fieldLoanAmount.setBounds (240, 110, 100, 25); 
              
              mine.add(fieldInterest); 
              fieldInterest.setBounds (240, 140, 100, 25); 
              
              mine.add(fieldDuration); 
              fieldDuration.setBounds (240, 170, 100, 25); 
              
              mine.add(LabelOr); 
              LabelOr.setBounds(80, 220, 400, 25); 
              
              mine.add (Calculate7); 
              Calculate7.setBounds (40, 260, 125, 30); 
              
              mine.add (Calculate15); 
              Calculate15.setBounds (180, 260, 125, 30); 
              
              mine.add (Calculate30); 
              Calculate30.setBounds (320, 260, 125, 30); 
              
              mine.add (Payment); 
              Payment.setBounds (130, 300, 100, 25); 
              
              mine.add (fieldPayment); 
              fieldPayment.setBounds (240, 300, 100, 25); 
              fieldPayment.setEditable (false); 
              
              mine.add (AmortizationTable); 
              AmortizationTable.setBounds (180, 330, 300, 25); 
              
              mine.add (scrollPane); 
              scrollPane.setBounds (50, 350, 380, 260); 
              areaAmortTable.setEditable(false); 
              
              mine.add (Clear); 
              Clear.setBounds (110, 620, 125, 30); 
              
              mine.add (Exit); 
              Exit.setBounds (250, 620, 125, 30); 
              
              this.setContentPane(mine); 
              this.pack(); 
              this.setTitle("Mortgage Amortization Calculator"); 
              
              setScreenSize(Toolkit.getDefaultToolkit().getScreenSize()); 
              setSize(500, 700); 
              } 
              public double loanAmount () 
              { 
              double loanAmount = Double.parseDouble(fieldLoanAmount.getText()); 
              return loanAmount; 
              } 
              
              public DecimalFormat getDecimalPlaces() { 
              return decimalPlaces; 
              } 
              
              public void setDecimalPlaces(DecimalFormat decimalPlaces) { 
              this.decimalPlaces = decimalPlaces; 
              } 
              
              public DecimalFormat getDecimalPlaces2() { 
              return decimalPlaces2; 
              } 
              
              public void setDecimalPlaces2(DecimalFormat decimalPlaces2) { 
              this.decimalPlaces2 = decimalPlaces2; 
              } 
              
              public DecimalFormat getDecimalPlaces4() { 
              return decimalPlaces4; 
              } 
              
              public void setDecimalPlaces4(DecimalFormat decimalPlaces4) { 
              this.decimalPlaces4 = decimalPlaces4; 
              } 
              
              public Dimension getScreenSize() { 
              return screenSize; 
              } 
              
              public void setScreenSize(Dimension screenSize) { 
              this.screenSize = screenSize; 
              } 
              
              public DecimalFormat getDecimalPlaces3() { 
              return decimalPlaces3; 
              } 
              
              public void setDecimalPlaces3(DecimalFormat decimalPlaces3) { 
              this.decimalPlaces3 = decimalPlaces3; 
              } 
              } 
              // end of program

              Comment

              • Eric Miles
                New Member
                • Feb 2012
                • 5

                #8
                It works for the calculation, but does not show the Amortization.

                Comment

                • neeraj0708
                  New Member
                  • Feb 2012
                  • 21

                  #9
                  Hi Eric,

                  Replace the for loop
                  for (int x = 1; x <=(Inter*12); x++){
                  inside Calculate event(at line number 51) as
                  for (int x = 1; x <=(Months*12) ; x++){
                  it will work fine.

                  Comment

                  • Eric Miles
                    New Member
                    • Feb 2012
                    • 5

                    #10
                    That did the trick, Thanks so much.

                    Comment

                    Working...