Java School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a Java Expert!

Join 307,102 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 2,019 people online right now. Registration is fast and FREE... Join Now!




Mortgage Calculator with GUI

 

Mortgage Calculator with GUI, Amortization won't calculate correctly

superczech

12 Nov, 2007 - 08:20 AM
Post #1

New D.I.C Head
*

Joined: 11 Nov, 2007
Posts: 3


My Contributions
Need some advice as to where I'm going wrong.

The code compiles and runs. Monthly payment is correct for each loan.
Problem is amortization numbers are wrong and each different loan seems to be wrong in a different way. Algorithms are the same for each.
Also the scroll bars in the amortization area are not present and amortization does not refresh (change) when different loans are chosen.

I'm at a loss at this point. Please help.

CODE

/**
* @(#)MortgageCalculatorServiceRequest5.java
*
* Week 3 Individual Assignment
*
* @version 1.00 2007/11/12
*
* 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.
* Please insert comments in the program to document the program.
*/


import java.text.*;
import java.math.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class MortgageCalculatorServiceRequest5a
{
    public static void main (String[] args)
    {
        JFrame window = new MortCalcGUI();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);
    }
}

class MortCalcGUI extends JFrame implements ActionListener
{
    //declare GUI function variables
    protected JButton bCalc7, bCalc15, bCalc30, bClear, bExit;
    protected JLabel labelPayment, labelLoanAmount, labelTitle, labelInstructions, labelAmortTable;
    protected JTextField fieldPayment, fieldLoanAmount;
    protected JTextArea areaAmortTable;

    //Declare variables & loan array and initialize with values
    double InterestPaid,PrinciplePaid,Balance,monthlyPay,loanAmount;
    int[] loanTerm = {7,15,30}; // loan term for 7 years, 15 years, and 30 years
    double[] intRate = {5.35,5.50,5.75}; // interest rates for 7 years, 15 years, and 30 years
    double loanAmt = loanAmount;
    

    public void actionPerformed (ActionEvent e)
    {
        //Perform actions based upon which button was pressed (provides looping function)
        if ("Calculate7".equals(e.getActionCommand()))
        {
            DecimalFormat decimalPlaces = new DecimalFormat("0.00");
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            
            double paymentAmount = CalculatePayment7();
            
            
            fieldPayment.setText("" + (currency.format(paymentAmount)));

            areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");

                    
            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/12)*Balance); //Monthly Interest paid
                    PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
                    Balance=(Balance-PrinciplePaid); //loan balance after payment
            
                              
                areaAmortTable.append (x + " \t " + currency.format(Balance) + " \t\t " + currency.format(InterestPaid)+"\n");
                  
                
            }
            
            
            if (Balance <= 0) //ending statement, balance at $0.00
            {
                areaAmortTable.append ("\tRemaining balance = $0.00");
                //paymentNumber = 0;
                //InterestPaid = 0.0;
            }
       }

        else if ("Calculate15".equals(e.getActionCommand()))
        {
            DecimalFormat decimalPlaces = new DecimalFormat("0.00");
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            
            double paymentAmount = CalculatePayment15 ();
            
            fieldPayment.setText("" + (currency.format(paymentAmount)));


            areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");

            
            for (int x = 1; x <=(loanTerm[1]*12); x++) //Loop through alll monthly payments for each loan
            {
                
                //Calculations on monthly payment
                    InterestPaid=((intRate[1]/100/12)*Balance); //Monthly Interest paid
                    PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
                    Balance=((Balance-PrinciplePaid)); //loan balance after payment

                areaAmortTable.append (x + " \t " + currency.format(Balance) + " \t\t " + currency.format(InterestPaid)+"\n");
            }
            if (loanAmt <= 0) //ending statement, balance at $0.00
            {
                areaAmortTable.append ("\tRemaining balance = $0.00");
                //paymentNumber = 0;
                //InterestPaid = 0.0;
            }

        }

        else if ("Calculate30".equals(e.getActionCommand()))
        {
            DecimalFormat decimalPlaces = new DecimalFormat("0.00");
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            
            double paymentAmount = CalculatePayment30 ();
            
            fieldPayment.setText("" + (currency.format(paymentAmount)));

            areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");

            
                    
            for (int x = 1; x <=(loanTerm[2]*12); x++) //Loop through alll monthly payments for each loan
            {
                              
                //Calculations on monthly payment
                    InterestPaid=((intRate[2]/100/12)*Balance); //Monthly Interest paid
                    PrinciplePaid=(paymentAmount-InterestPaid); //Applied towards principle
                    Balance=((Balance-PrinciplePaid)); //loan balance after payment

                areaAmortTable.append (x + " \t " + currency.format(Balance) + " \t\t " + currency.format(InterestPaid)+"\n");
            }
            
            if (loanAmt <= 0) //ending statement, balance at $0.00
            {
                areaAmortTable.append ("\tRemaining balance = $0.00");
                //paymentNumber = 0;
                //InterestPaid = 0.0;
            }

        }

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

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

    public double CalculatePayment7 ()
    {
    
        //Check for valid numeric imput
        try
        {
            //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 if input is invalid
            JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return 0;
        }
    }

    public double CalculatePayment15 ()
    {
        //Check for valid numeric imput
        try
        {
            //Perform payment calculations if input is valid
            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 if input is invalid
            JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return 0;
        }
    }
    public double CalculatePayment30 ()
    {
        //Check for valid numeric imput
        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 if input is invalid
            JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return 0;
        }
    }


    public void ClearFields ()
    {
        //Set all text fields to blank
        fieldPayment.setText ("");
        fieldLoanAmount.setText ("");
        areaAmortTable.setText ("");
    }

    public MortCalcGUI ()
    {
        //Set up and initialize buttons for GUI
        bCalc7 = new JButton ("7 Year, 5.35%");
        bCalc7.setActionCommand ("Calculate7");
        bCalc15 = new JButton ("15 Year, 5.50%");
        bCalc15.setActionCommand ("Calculate15");
        bCalc30 = new JButton ("30 Year, 5.75%");
        bCalc30.setActionCommand ("Calculate30");
        bClear = new JButton ("Clear All Fields");
        bClear.setActionCommand ("Clear");
        bExit = new JButton ("Exit Program");
        bExit.setActionCommand ("Exit");

        //Set up labels and field sizes for GUI
        labelTitle = new JLabel ("Welcome to the Mortgage Calculator V5.0");
        labelInstructions = new JLabel ("Enter the amount of the loan and then choose the term/rate of the loan.");
        labelPayment = new JLabel ("Monthly Payment:");
        labelLoanAmount = new JLabel ("Amount of Loan:");
        fieldPayment = new JTextField ("", 12);
        fieldLoanAmount = new JTextField ("", 10);
        labelAmortTable = new JLabel ("Amortization Table");
        areaAmortTable = new JTextArea (10, 300);

        JScrollPane scrollPane = new JScrollPane (areaAmortTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        //Set up listeners for each button
        bCalc7.addActionListener(this);
        bCalc15.addActionListener(this);
        bCalc30.addActionListener(this);
        bClear.addActionListener(this);
        bExit.addActionListener(this);

        //Construct GUI and set layout
        JPanel mine = new JPanel();
        mine.setLayout (null);

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

        mine.add (labelInstructions);
        labelInstructions.setBounds (30, 70, 450, 15);

        mine.add (labelLoanAmount);
        labelLoanAmount.setBounds (130, 110, 100, 25);

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

        mine.add (bCalc7);
        bCalc7.setBounds (40, 150, 125, 30);

        mine.add (bCalc15);
        bCalc15.setBounds (180, 150, 125, 30);

        mine.add (bCalc30);
        bCalc30.setBounds (320, 150, 125, 30);

        mine.add (labelPayment);
        labelPayment.setBounds (130, 200, 100, 25);

        mine.add (fieldPayment);
        fieldPayment.setBounds (240, 200, 100, 25);
        fieldPayment.setEditable (false);

        mine.add (labelAmortTable);
        labelAmortTable.setBounds (180, 250, 300, 25);

        mine.add (areaAmortTable);
        areaAmortTable.setBounds (50, 280, 400, 270);
        areaAmortTable.setEditable (false);

        mine.add (scrollPane);

        mine.add (bClear);
        bClear.setBounds (110, 570, 125, 30);

        mine.add (bExit);
        bExit.setBounds (250, 570, 125, 30);

        this.setContentPane(mine);
        this.pack();
        this.setTitle("Mortgage Calculator V5.0");

        //Set window size
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(500, 700);
    }
    public double loanAmount ()
    {
        double loanAmount = Double.parseDouble(fieldLoanAmount.getText());
        return loanAmount;
    }
}





User is offlineProfile CardPM
+Quote Post


Martyr2

RE: Mortgage Calculator With GUI

12 Nov, 2007 - 10:21 AM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 7,307



Thanked: 837 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Hello superczech,

You had a few problems I have managed to iron out for you. Here is a list of things that were wrong...

1) You forgot to set your initial loanAmt to what was in the fieldloanAmount field. You had your balance set to loanAmount but you never set loanAmount. So at the beginning of each calculation (after where you append the header to your amortization table) I have set loanAmt with the field value.

2) During each part of the loop, you were also not resetting your loanAmt to the final balance. You had Balance = loanAmt; but you were not adjusting loanAmt after each iteration. I used loanAmt as the end result instead of balance and added it to the table, then balance will get set to loanAmt at the top of each iteration.

3) Your scrollpane... you setup your scrollpane and added the table just fine, but then you attempt to add the table AND the pane. Remember that when you add the table to the pane, it is now just the pane. It is a container. So add just the pane. I have added comments to show you that part in the GUI.

Other than that, all is moving in the right direction. You might want to consider refactoring some of your calculations into one function, it would reduce your code drastically. Just a future improvement tip.

Here is the finished code...

CODE

/**
* @(#)MortgageCalculatorServiceRequest5.java
*
* Week 3 Individual Assignment
*
* @version 1.00 2007/11/12
*
* 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.
* Please insert comments in the program to document the program.
*/


import java.text.*;
import java.math.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class MortgageCalculatorServiceRequest5a
{
    public static void main (String[] args)
    {
        JFrame window = new MortCalcGUI();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);
    }
}

class MortCalcGUI extends JFrame implements ActionListener
{
    //declare GUI function variables
    protected JButton bCalc7, bCalc15, bCalc30, bClear, bExit;
    protected JLabel labelPayment, labelLoanAmount, labelTitle, labelInstructions, labelAmortTable;
    protected JTextField fieldPayment, fieldLoanAmount;
    protected JTextArea areaAmortTable;


    //Declare variables & loan array and initialize with values
    double InterestPaid,PrinciplePaid,Balance,monthlyPay,loanAmount;
    int[] loanTerm = {7,15,30}; // loan term for 7 years, 15 years, and 30 years
    double[] intRate = {5.35,5.50,5.75}; // interest rates for 7 years, 15 years, and 30 years
    double loanAmt = loanAmount;
    

    public void actionPerformed (ActionEvent e)
    {
        //Perform actions based upon which button was pressed (provides looping function)
        if ("Calculate7".equals(e.getActionCommand()))
        {
            DecimalFormat decimalPlaces = new DecimalFormat("0.00");
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            
            double paymentAmount = CalculatePayment7();
            
            
            fieldPayment.setText("" + (currency.format(paymentAmount)));

            areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");

            // Need to set the loan amount to the value from the field first
            // You need to do this for each of your loan calculations for 7, 15, and 30 years.
            loanAmt = Double.parseDouble(fieldLoanAmount.getText());
                    
            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");
                //paymentNumber = 0;
                //InterestPaid = 0.0;
            }
       }

        else if ("Calculate15".equals(e.getActionCommand()))
        {
            DecimalFormat decimalPlaces = new DecimalFormat("0.00");
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            
            double paymentAmount = CalculatePayment15 ();
            
            fieldPayment.setText("" + (currency.format(paymentAmount)));


            areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");
            loanAmt = Double.parseDouble(fieldLoanAmount.getText());
            
            for (int x = 1; x <=(loanTerm[1]*12); x++) //Loop through all monthly payments for each loan
            {

                    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");
                //paymentNumber = 0;
                //InterestPaid = 0.0;
            }

        }

        else if ("Calculate30".equals(e.getActionCommand()))
        {
            DecimalFormat decimalPlaces = new DecimalFormat("0.00");
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            
            double paymentAmount = CalculatePayment30 ();
            
            fieldPayment.setText("" + (currency.format(paymentAmount)));

            areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");
            loanAmt = Double.parseDouble(fieldLoanAmount.getText());
            
                    
            for (int x = 1; x <=(loanTerm[2]*12); x++) //Loop through alll monthly payments for each loan
            {
                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");
                //paymentNumber = 0;
                //InterestPaid = 0.0;
            }

        }

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

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

    public double CalculatePayment7 ()
    {
    
        //Check for valid numeric imput
        try
        {
            //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 if input is invalid
            JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return 0;
        }
    }

    public double CalculatePayment15 ()
    {
        //Check for valid numeric imput
        try
        {
            //Perform payment calculations if input is valid
            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 if input is invalid
            JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return 0;
        }
    }

    public double CalculatePayment30 ()
    {
        //Check for valid numeric imput
        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 if input is invalid
            JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return 0;
        }
    }


    public void ClearFields ()
    {
        //Set all text fields to blank
        fieldPayment.setText ("");
        fieldLoanAmount.setText ("");
        areaAmortTable.setText ("");
    }

    public MortCalcGUI ()
    {
        //Set up and initialize buttons for GUI
        bCalc7 = new JButton ("7 Year, 5.35%");
        bCalc7.setActionCommand ("Calculate7");
        bCalc15 = new JButton ("15 Year, 5.50%");
        bCalc15.setActionCommand ("Calculate15");
        bCalc30 = new JButton ("30 Year, 5.75%");
        bCalc30.setActionCommand ("Calculate30");
        bClear = new JButton ("Clear All Fields");
        bClear.setActionCommand ("Clear");
        bExit = new JButton ("Exit Program");
        bExit.setActionCommand ("Exit");

        //Set up labels and field sizes for GUI
        labelTitle = new JLabel ("Welcome to the Mortgage Calculator V5.0");
        labelInstructions = new JLabel ("Enter the amount of the loan and then choose the term/rate of the loan.");

        labelPayment = new JLabel ("Monthly Payment:");
        labelLoanAmount = new JLabel ("Amount of Loan:");
        fieldPayment = new JTextField ("", 12);
        fieldLoanAmount = new JTextField ("", 10);
        labelAmortTable = new JLabel ("Amortization Table");
        areaAmortTable = new JTextArea (10, 300);

        JScrollPane scrollPane = new JScrollPane (areaAmortTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        //Set up listeners for each button
        bCalc7.addActionListener(this);
        bCalc15.addActionListener(this);
        bCalc30.addActionListener(this);
        bClear.addActionListener(this);
        bExit.addActionListener(this);

        //Construct GUI and set layout
        JPanel mine = new JPanel();
        mine.setLayout (null);

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

        mine.add (labelInstructions);
        labelInstructions.setBounds (30, 70, 450, 15);

        mine.add (labelLoanAmount);
        labelLoanAmount.setBounds (130, 110, 100, 25);

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

        mine.add (bCalc7);
        bCalc7.setBounds (40, 150, 125, 30);

        mine.add (bCalc15);
        bCalc15.setBounds (180, 150, 125, 30);

        mine.add (bCalc30);
        bCalc30.setBounds (320, 150, 125, 30);

        mine.add (labelPayment);
        labelPayment.setBounds (130, 200, 100, 25);

        mine.add (fieldPayment);
        fieldPayment.setBounds (240, 200, 100, 25);
        fieldPayment.setEditable (false);

        mine.add (labelAmortTable);
        labelAmortTable.setBounds (180, 250, 300, 25);


        // Add the scrollpane, set its bounds and set the table as not editable.
        // Table is part of scrollpane now, so add and place only the scrollpane.

        mine.add (scrollPane);
        scrollPane.setBounds (50, 280, 400, 270);
        areaAmortTable.setEditable(false);

        mine.add (bClear);
        bClear.setBounds (110, 570, 125, 30);

        mine.add (bExit);
        bExit.setBounds (250, 570, 125, 30);

        this.setContentPane(mine);
        this.pack();
        this.setTitle("Mortgage Calculator V5.0");

        //Set window size
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(500, 700);
    }
    public double loanAmount ()
    {
        double loanAmount = Double.parseDouble(fieldLoanAmount.getText());
        return loanAmount;
    }
}


Enjoy!

"At DIC we be mortgage calculating killer ninjas!" decap.gif
User is offlineProfile CardPM
+Quote Post

superczech

RE: Mortgage Calculator With GUI

12 Nov, 2007 - 12:46 PM
Post #3

New D.I.C Head
*

Joined: 11 Nov, 2007
Posts: 3


My Contributions
QUOTE(Martyr2 @ 12 Nov, 2007 - 11:21 AM) *

Hello superczech,

You had a few problems I have managed to iron out for you. Here is a list of things that were wrong...

1) You forgot to set your initial loanAmt to what was in the fieldloanAmount field. You had your balance set to loanAmount but you never set loanAmount. So at the beginning of each calculation (after where you append the header to your amortization table) I have set loanAmt with the field value.

2) During each part of the loop, you were also not resetting your loanAmt to the final balance. You had Balance = loanAmt; but you were not adjusting loanAmt after each iteration. I used loanAmt as the end result instead of balance and added it to the table, then balance will get set to loanAmt at the top of each iteration.

3) Your scrollpane... you setup your scrollpane and added the table just fine, but then you attempt to add the table AND the pane. Remember that when you add the table to the pane, it is now just the pane. It is a container. So add just the pane. I have added comments to show you that part in the GUI.

Other than that, all is moving in the right direction. You might want to consider refactoring some of your calculations into one function, it would reduce your code drastically. Just a future improvement tip.

Here is the finished code...

CODE

/**
* @(#)MortgageCalculatorServiceRequest5.java
*
* Week 3 Individual Assignment
*
* @version 1.00 2007/11/12
*
* 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.
* Please insert comments in the program to document the program.
*/


import java.text.*;
import java.math.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class MortgageCalculatorServiceRequest5a
{
    public static void main (String[] args)
    {
        JFrame window = new MortCalcGUI();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);
    }
}

class MortCalcGUI extends JFrame implements ActionListener
{
    //declare GUI function variables
    protected JButton bCalc7, bCalc15, bCalc30, bClear, bExit;
    protected JLabel labelPayment, labelLoanAmount, labelTitle, labelInstructions, labelAmortTable;
    protected JTextField fieldPayment, fieldLoanAmount;
    protected JTextArea areaAmortTable;


    //Declare variables & loan array and initialize with values
    double InterestPaid,PrinciplePaid,Balance,monthlyPay,loanAmount;
    int[] loanTerm = {7,15,30}; // loan term for 7 years, 15 years, and 30 years
    double[] intRate = {5.35,5.50,5.75}; // interest rates for 7 years, 15 years, and 30 years
    double loanAmt = loanAmount;
    

    public void actionPerformed (ActionEvent e)
    {
        //Perform actions based upon which button was pressed (provides looping function)
        if ("Calculate7".equals(e.getActionCommand()))
        {
            DecimalFormat decimalPlaces = new DecimalFormat("0.00");
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            
            double paymentAmount = CalculatePayment7();
            
            
            fieldPayment.setText("" + (currency.format(paymentAmount)));

            areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");

            // Need to set the loan amount to the value from the field first
            // You need to do this for each of your loan calculations for 7, 15, and 30 years.
            loanAmt = Double.parseDouble(fieldLoanAmount.getText());
                    
            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");
                //paymentNumber = 0;
                //InterestPaid = 0.0;
            }
       }

        else if ("Calculate15".equals(e.getActionCommand()))
        {
            DecimalFormat decimalPlaces = new DecimalFormat("0.00");
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            
            double paymentAmount = CalculatePayment15 ();
            
            fieldPayment.setText("" + (currency.format(paymentAmount)));


            areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");
            loanAmt = Double.parseDouble(fieldLoanAmount.getText());
            
            for (int x = 1; x <=(loanTerm[1]*12); x++) //Loop through all monthly payments for each loan
            {

                    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");
                //paymentNumber = 0;
                //InterestPaid = 0.0;
            }

        }

        else if ("Calculate30".equals(e.getActionCommand()))
        {
            DecimalFormat decimalPlaces = new DecimalFormat("0.00");
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            
            double paymentAmount = CalculatePayment30 ();
            
            fieldPayment.setText("" + (currency.format(paymentAmount)));

            areaAmortTable.append ("Payment # \t Remaining Balance \t  Interest Paid\n");
            loanAmt = Double.parseDouble(fieldLoanAmount.getText());
            
                    
            for (int x = 1; x <=(loanTerm[2]*12); x++) //Loop through alll monthly payments for each loan
            {
                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");
                //paymentNumber = 0;
                //InterestPaid = 0.0;
            }

        }

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

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

    public double CalculatePayment7 ()
    {
    
        //Check for valid numeric imput
        try
        {
            //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 if input is invalid
            JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return 0;
        }
    }

    public double CalculatePayment15 ()
    {
        //Check for valid numeric imput
        try
        {
            //Perform payment calculations if input is valid
            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 if input is invalid
            JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return 0;
        }
    }

    public double CalculatePayment30 ()
    {
        //Check for valid numeric imput
        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 if input is invalid
            JOptionPane.showMessageDialog(null, " Invalid Entry!\nPlease enter only numeric values!!", "ERROR", JOptionPane.ERROR_MESSAGE);
            return 0;
        }
    }


    public void ClearFields ()
    {
        //Set all text fields to blank
        fieldPayment.setText ("");
        fieldLoanAmount.setText ("");
        areaAmortTable.setText ("");
    }

    public MortCalcGUI ()
    {
        //Set up and initialize buttons for GUI
        bCalc7 = new JButton ("7 Year, 5.35%");
        bCalc7.setActionCommand ("Calculate7");
        bCalc15 = new JButton ("15 Year, 5.50%");
        bCalc15.setActionCommand ("Calculate15");
        bCalc30 = new JButton ("30 Year, 5.75%");
        bCalc30.setActionCommand ("Calculate30");
        bClear = new JButton ("Clear All Fields");
        bClear.setActionCommand ("Clear");
        bExit = new JButton ("Exit Program");
        bExit.setActionCommand ("Exit");

        //Set up labels and field sizes for GUI
        labelTitle = new JLabel ("Welcome to the Mortgage Calculator V5.0");
        labelInstructions = new JLabel ("Enter the amount of the loan and then choose the term/rate of the loan.");

        labelPayment = new JLabel ("Monthly Payment:");
        labelLoanAmount = new JLabel ("Amount of Loan:");
        fieldPayment = new JTextField ("", 12);
        fieldLoanAmount = new JTextField ("", 10);
        labelAmortTable = new JLabel ("Amortization Table");
        areaAmortTable = new JTextArea (10, 300);

        JScrollPane scrollPane = new JScrollPane (areaAmortTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        //Set up listeners for each button
        bCalc7.addActionListener(this);
        bCalc15.addActionListener(this);
        bCalc30.addActionListener(this);
        bClear.addActionListener(this);
        bExit.addActionListener(this);

        //Construct GUI and set layout
        JPanel mine = new JPanel();
        mine.setLayout (null);

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

        mine.add (labelInstructions);
        labelInstructions.setBounds (30, 70, 450, 15);

        mine.add (labelLoanAmount);
        labelLoanAmount.setBounds (130, 110, 100, 25);

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

        mine.add (bCalc7);
        bCalc7.setBounds (40, 150, 125, 30);

        mine.add (bCalc15);
        bCalc15.setBounds (180, 150, 125, 30);

        mine.add (bCalc30);
        bCalc30.setBounds (320, 150, 125, 30);

        mine.add (labelPayment);
        labelPayment.setBounds (130, 200, 100, 25);

        mine.add (fieldPayment);
        fieldPayment.setBounds (240, 200, 100, 25);
        fieldPayment.setEditable (false);

        mine.add (labelAmortTable);
        labelAmortTable.setBounds (180, 250, 300, 25);


        // Add the scrollpane, set its bounds and set the table as not editable.
        // Table is part of scrollpane now, so add and place only the scrollpane.

        mine.add (scrollPane);
        scrollPane.setBounds (50, 280, 400, 270);
        areaAmortTable.setEditable(false);

        mine.add (bClear);
        bClear.setBounds (110, 570, 125, 30);

        mine.add (bExit);
        bExit.setBounds (250, 570, 125, 30);

        this.setContentPane(mine);
        this.pack();
        this.setTitle("Mortgage Calculator V5.0");

        //Set window size
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(500, 700);
    }
    public double loanAmount ()
    {
        double loanAmount = Double.parseDouble(fieldLoanAmount.getText());
        return loanAmount;
    }
}


Enjoy!

"At DIC we be mortgage calculating killer ninjas!" decap.gif


Thank you for your help. I'll check out the changes you made and also the recommendations. I'm very new to this and quite confused most of the time. Thanks again.

User is offlineProfile CardPM
+Quote Post

n2java1

RE: Mortgage Calculator With GUI

28 Nov, 2007 - 09:27 AM
Post #4

New D.I.C Head
*

Joined: 28 Nov, 2007
Posts: 2


My Contributions
Martyr2:
I also benefit from your answer. Can you please guide me on Netbeans using this code? I am new to Java and Netbeans.
Thanks,
smile.gif
n2java1
User is offlineProfile CardPM
+Quote Post

Martyr2

RE: Mortgage Calculator With GUI

28 Nov, 2007 - 11:22 AM
Post #5

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 7,307



Thanked: 837 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Can you provide some code so we can take a look at where you might be going wrong? We are always willing to help those who need it but ask that you help us help you by presenting what you have going already. Thanks! smile.gif
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 12:22PM

Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month