• Support PF! Buy your school textbooks, materials and every day products Here!

Java GUI Mortgage Calculator

  • #1
117
3
Ok, Here is the assignment:

Develop a mortgage payment calculator. Design a GUI to enter price of home, down payment, interest rate. Your bank only offers 10, 15, and 30 year mortgages. Use grouped radio buttons to select between 10, 15, or 30 year mortgage. Monthly payment should be calculated by the application.


Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MortgagePaymentCalculator.java
 *
 * Created on Jan 26, 2011, 1:45:34 PM
 */

package my.calculator;
import javax.swing.JOptionPane;
import java.util.Scanner;
/**
 *
 * @author Jon and Jessica
 */
public class MortgagePaymentCalculator extends javax.swing.JFrame {

    /** Creates new form MortgagePaymentCalculator */
    public MortgagePaymentCalculator() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        price = new javax.swing.JTextField();
        downPayment = new javax.swing.JTextField();
        interestRate = new javax.swing.JTextField();
        months1 = new javax.swing.JRadioButton();
        months2 = new javax.swing.JRadioButton();
        months3 = new javax.swing.JRadioButton();
        jLabel5 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        monthlyPayment = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Mortgage Payment Calculator");

        jLabel2.setText("Price of Home:");

        jLabel3.setText("Down Payment:");

        jLabel4.setText("Interest Rate:");

        price.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                priceActionPerformed(evt);
            }
        });

        downPayment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                downPaymentActionPerformed(evt);
            }
        });

        interestRate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                interestRateActionPerformed(evt);
            }
        });

        buttonGroup1.add(months1);
        months1.setText("10 Year Mortgage");
        months1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                months1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(months2);
        months2.setText("15 Year Mortgage");
        months2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                months2ActionPerformed(evt);
            }
        });

        buttonGroup1.add(months3);
        months3.setText("30 Year Mortgage");
        months3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                months3ActionPerformed(evt);
            }
        });

        jLabel5.setText("Monthly Payment:");

        jButton1.setText("Calculate Payment");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Quit");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(monthlyPayment, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(months3)
                                    .addComponent(months2)
                                    .addComponent(months1)
                                    .addComponent(jButton2)))))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(price, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                        .addComponent(downPayment, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(interestRate, javax.swing.GroupLayout.Alignment.LEADING)))
                .addGap(146, 146, 146))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(months1)
                        .addGap(11, 11, 11)
                        .addComponent(months2)
                        .addGap(6, 6, 6)
                        .addComponent(months3))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(downPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(interestRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(monthlyPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(31, 31, 31))
        );

        pack();
    }// </editor-fold>

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        System.exit(0);
    }                                        

    private void priceActionPerformed(java.awt.event.ActionEvent evt) {
        // User enters total price of home to be bought
        Scanner input = new Scanner(System.in);
        double price = input.nextDouble();

    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // On click of calculate button, the monthly payment is calculated
        // and output to the monthly payment text box
        double payment = 0;
        
        monthlyPayment.setText(String.valueOf(payment));
    }

    private void downPaymentActionPerformed(java.awt.event.ActionEvent evt) {
        // Accept user input for the amount of the down payment
        // for calculating monthly payments
        Scanner input = new Scanner(System.in);
        double downPayment = input.nextDouble();
    }

    private void interestRateActionPerformed(java.awt.event.ActionEvent evt) {
        // Accept user input for the amount of the interest rate for calculating monthly payment
        Scanner input = new Scanner(System.in);
        double interestRate = input.nextDouble();
    
    }

    private void months1ActionPerformed(java.awt.event.ActionEvent evt) {
        // Calculate the interest based on a 10 year loan
        int months = 120;
    }

    private void months2ActionPerformed(java.awt.event.ActionEvent evt) {
        // Calculate the interest based on a 15 year loan
        int months = 180;
    }

    private void months3ActionPerformed(java.awt.event.ActionEvent evt) {
        // Calculate the interest based on a 30 year loan
        int months = 360;
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MortgagePaymentCalculator().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JTextField downPayment;
    private javax.swing.JTextField interestRate;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField monthlyPayment;
    private javax.swing.JRadioButton months1;
    private javax.swing.JRadioButton months2;
    private javax.swing.JRadioButton months3;
    private javax.swing.JTextField price;
    // End of variables declaration

}
I have created the GUI with text field for Price of home (variable price), down payment (variable downPayment), and interest rate (variable interestRate).

I need to accept user input from the text boxes, calculate the mortgage, based on 10, 15, or 30 year mortgage that is dictated by a radio button.

I can't figure out what the next step I need is. Could someone take a look at the code and point me in the right direction. I have the Quit button working, but that is about it.
 

Answers and Replies

  • #2
33,506
5,192
It looks to me like you need to fill in the rest of this method:
Code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // On click of calculate button, the monthly payment is calculated
        // and output to the monthly payment text box
        double payment = 0;
        
        monthlyPayment.setText(String.valueOf(payment));
    }
This method (or more likely event handler) needs to take the entered values for mortgage amount, down payment, interest rate, and no. of months and calculate the payment, which it places in the appropriate text box.

I don't know the formula off the top of my head, but I've done similar kinds of applications before in VB, when my son was taking a class that used that language.

This event handler needs to be able to pop up some warning if the user hasn't entered all the data needed for the calculation.

Does that help?
 
  • #3
117
3
Ok, so I figured out how to parse the input from string to double, float, etc. and I am slowly hammering out the actual formula, but I am having a bit of trouble figuring out how to implement the use of the radio button in the formula. New code as follows:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MortgagePaymentCalculator.java
 *
 * Created on Jan 26, 2011, 1:45:34 PM
 */

package my.calculator;
import javax.swing.JOptionPane;
import java.util.Scanner;
import java.text.DecimalFormat;
/**
 *
 * @author Jon and Jessica
 */
public class MortgagePaymentCalculator extends javax.swing.JFrame {

    /** Creates new form MortgagePaymentCalculator */
    public MortgagePaymentCalculator() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        price = new javax.swing.JTextField();
        downPayment = new javax.swing.JTextField();
        interestRate = new javax.swing.JTextField();
        months1 = new javax.swing.JRadioButton();
        months2 = new javax.swing.JRadioButton();
        months3 = new javax.swing.JRadioButton();
        jLabel5 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        monthlyPayment = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Mortgage Payment Calculator");

        jLabel2.setText("Price of Home:");

        jLabel3.setText("Down Payment:");

        jLabel4.setText("Interest Rate:");

        price.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                priceMouseMoved(evt);
            }
        });
        price.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                priceActionPerformed(evt);
            }
        });

        downPayment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                downPaymentActionPerformed(evt);
            }
        });

        interestRate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                interestRateActionPerformed(evt);
            }
        });

        buttonGroup1.add(months1);
        months1.setText("10 Year Mortgage");
        months1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                months1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(months2);
        months2.setText("15 Year Mortgage");
        months2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                months2ActionPerformed(evt);
            }
        });

        buttonGroup1.add(months3);
        months3.setText("30 Year Mortgage");
        months3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                months3ActionPerformed(evt);
            }
        });

        jLabel5.setText("Monthly Payment:");

        jButton1.setText("Calculate Payment");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Quit");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Clear Form");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(137, 137, 137)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton1)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton2))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(monthlyPayment, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(price, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                                    .addComponent(downPayment, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(interestRate, javax.swing.GroupLayout.Alignment.LEADING))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(months3)
                                    .addComponent(months2)
                                    .addComponent(months1))))))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2, jButton3});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(downPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(interestRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(monthlyPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(months1)
                        .addGap(11, 11, 11)
                        .addComponent(months2)
                        .addGap(6, 6, 6)
                        .addComponent(months3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton3)
                    .addComponent(jButton2))
                .addGap(53, 53, 53))
        );

        pack();
    }// </editor-fold>

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        System.exit(0);
    }                                        

    private void priceActionPerformed(java.awt.event.ActionEvent evt) {
        // User enters total price of home to be bought
        Scanner input = new Scanner(System.in);
        double price = input.nextDouble();

    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // On click of calculate button, the monthly payment is calculated
        // and output to the monthly payment text box
        
        DecimalFormat money = new DecimalFormat("$0.00"); // Format the text as U.S. Dollars
        double payment = ((Double.parseDouble(price.getText())- Double.parseDouble(downPayment.getText()))*
                (Float.parseFloat(interestRate.getText())));
        monthlyPayment.setText(String.valueOf(money.format(payment)));
    }

    private void downPaymentActionPerformed(java.awt.event.ActionEvent evt) {
        // Accept user input for the amount of the down payment
        // for calculating monthly payments
       
    }

    private void interestRateActionPerformed(java.awt.event.ActionEvent evt) {
        // Accept user input for the amount of the interest rate for calculating monthly payment
        
    
    }

    private void months1ActionPerformed(java.awt.event.ActionEvent evt) {
        // Calculate the interest based on a 10 year loan
        int months = 120;
    }

    private void months2ActionPerformed(java.awt.event.ActionEvent evt) {
        // Calculate the interest based on a 15 year loan
        int months = 180;
    }

    private void months3ActionPerformed(java.awt.event.ActionEvent evt) {
        // Calculate the interest based on a 30 year loan
        int months = 360;
    }

    private void priceMouseMoved(java.awt.event.MouseEvent evt) {
        // When mouse hovers over text field display text

    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        // When the clear button is pressed, clear all text fields
        price.setText("");
        downPayment.setText("");
        interestRate.setText("");
        monthlyPayment.setText("");

    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MortgagePaymentCalculator().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JTextField downPayment;
    private javax.swing.JTextField interestRate;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField monthlyPayment;
    private javax.swing.JRadioButton months1;
    private javax.swing.JRadioButton months2;
    private javax.swing.JRadioButton months3;
    private javax.swing.JTextField price;
    // End of variables declaration

}
Here is where I have implemented the formula for calculating the payment, but I still need to figure out how to use the selected radio button in the formula.

Code:
 // On click of calculate button, the monthly payment is calculated
        // and output to the monthly payment text box
        
        DecimalFormat money = new DecimalFormat("$0.00"); // Format the text as U.S. Dollars
        double payment = ((Double.parseDouble(price.getText())- Double.parseDouble(downPayment.getText()))*
                (Float.parseFloat(interestRate.getText())));
        monthlyPayment.setText(String.valueOf(money.format(payment)));
    }
What is the code to call the radio button?
 
Last edited:
  • #4
117
3
Ok, so now I have figured out the radio buttons using nested if statements:

Code:
// Get the radio button selected
           if (months1.isSelected()){
           months = 120;
           }
                else if (months2.isSelected()){
                months = 180;
           }
                        else if (months3.isSelected()){
                        months = 360;
           }
But my formula is wrong. I keep getting HUGE monthly payments. Anyone know what I screwed up on the formula?

Code:
double payment = ((Double.parseDouble(price.getText())- Double.parseDouble(downPayment.getText()))*
                ((Float.parseFloat(interestRate.getText())) / months));
 
  • #5
117
3
Problem Solved, mortgage calculator runs. Figuring out the correct formula was a pain in the butt, but I got it working. I can't figure out why, but the payment comes out $0.01 over (and sometimes under, depending on the interest rate) the actual payment calculated by other mortgage calculators, but I think I can live with that, unless someone can help me figure out why it is adding the penny in.

Here is completed code:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MortgagePaymentCalculator.java
 *
 * Created on Jan 26, 2011, 1:45:34 PM
 */

package my.calculator;
import java.text.DecimalFormat;
/**
 *
 * @author Jonathan Smith
 * Develop a mortgage payment calculator. Design a GUI to enter price of home, down payment, interest rate.
 * Your bank only offers 10, 15, and 30 year mortgages.
 * Use grouped radio buttons to select between 10, 15, or 30 year mortgage.
 * Monthly payment should be calculated by the application.
 */
public class MortgagePaymentCalculator extends javax.swing.JFrame {

    /** Creates new form MortgagePaymentCalculator */
    public MortgagePaymentCalculator() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        price = new javax.swing.JTextField();
        downPayment = new javax.swing.JTextField();
        interestRate = new javax.swing.JTextField();
        months1 = new javax.swing.JRadioButton();
        months2 = new javax.swing.JRadioButton();
        months3 = new javax.swing.JRadioButton();
        jLabel5 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        monthlyPayment = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Mortgage Payment Calculator");

        jLabel2.setText("Price of Home:");

        jLabel3.setText("Down Payment:");

        jLabel4.setText("Interest Rate:");

        price.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                priceMouseMoved(evt);
            }
        });
        price.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                priceActionPerformed(evt);
            }
        });

        downPayment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                downPaymentActionPerformed(evt);
            }
        });

        interestRate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                interestRateActionPerformed(evt);
            }
        });

        buttonGroup1.add(months1);
        months1.setText("10 Year Mortgage");
        months1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                months1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(months2);
        months2.setText("15 Year Mortgage");
        months2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                months2ActionPerformed(evt);
            }
        });

        buttonGroup1.add(months3);
        months3.setText("30 Year Mortgage");
        months3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                months3ActionPerformed(evt);
            }
        });

        jLabel5.setText("Monthly Payment:");

        jButton1.setText("Calculate Payment");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Quit");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Clear Form");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(137, 137, 137)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton1)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton2))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(monthlyPayment, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(price, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                                    .addComponent(downPayment, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(interestRate, javax.swing.GroupLayout.Alignment.LEADING))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(months3)
                                    .addComponent(months2)
                                    .addComponent(months1))))))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jButton2, jButton3});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(downPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(interestRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(monthlyPayment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(months1)
                        .addGap(11, 11, 11)
                        .addComponent(months2)
                        .addGap(6, 6, 6)
                        .addComponent(months3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton3)
                    .addComponent(jButton2))
                .addGap(53, 53, 53))
        );

        pack();
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        System.exit(0);
    }                                        

    private void priceActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // User enters total price of home to be bought
        
    }                                     

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // On click of calculate button, the monthly payment is calculated
        // and output to the monthly payment text box
        int months = 0;
        double principle = Double.parseDouble(price.getText());
        double payment = Double.parseDouble(downPayment.getText());
        float interest = ((Float.parseFloat(interestRate.getText())/ 12) / 100);
        double loan = (principle - payment);

        
        DecimalFormat money = new DecimalFormat("$0.00"); // Format the text as U.S. Dollars
        
        // Use grouped radio buttons to select between 10, 15, or 30 year mortgage.
        // Get the radio button selected
           if (months1.isSelected()){
           months = 120;
           }
                else if (months2.isSelected()){
                months = 180;
           }
                        else if (months3.isSelected()){
                        months = 360;
           }
        // Monthly payment should be calculated by the application.
        // Calculate monthly payment
        double yourPayment = ((loan * interest) / (1 - Math.pow(1 / (1 + interest), months)));
        
        
        // Output monthly payment formatted as U.S. Dollars ($0.00)
        monthlyPayment.setText(String.valueOf(money.format(yourPayment)));
    }                                        

    private void downPaymentActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // Accept user input for the amount of the down payment
        // for calculating monthly payments
       
    }                                           

    private void interestRateActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // Accept user input for the amount of the interest rate for calculating monthly payment
        
    
    }                                            

    private void months1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // Calculate the interest based on a 10 year loan
                
    }                                       

    private void months2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // Calculate the interest based on a 15 year loan
                
    }                                       

    private void months3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // Calculate the interest based on a 30 year loan
                
    }                                       

    private void priceMouseMoved(java.awt.event.MouseEvent evt) {                                 
        // When mouse hovers over text field display text

    }                                

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // When the clear button is pressed, clear all text fields
        price.setText("");
        downPayment.setText("");
        interestRate.setText("");
        monthlyPayment.setText("");
        buttonGroup1.clearSelection();


    }                                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MortgagePaymentCalculator().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JTextField downPayment;
    private javax.swing.JTextField interestRate;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField monthlyPayment;
    private javax.swing.JRadioButton months1;
    private javax.swing.JRadioButton months2;
    private javax.swing.JRadioButton months3;
    private javax.swing.JTextField price;
    // End of variables declaration                   

}
and to make it easy to find, here is the algorithm for calculating the monthly payments:

variable declarations:

Code:
int months = 0;
        double principle = Double.parseDouble(price.getText());
        double payment = Double.parseDouble(downPayment.getText());
        float interest = ((Float.parseFloat(interestRate.getText())/ 12) / 100);
        double loan = (principle - payment);
actual algorithm
Code:
double yourPayment = ((loan * interest) / (1 - Math.pow(1 / (1 + interest), months)));
 
  • #6
33,506
5,192
Ok, so now I have figured out the radio buttons using nested if statements:

Code:
// Get the radio button selected
           if (months1.isSelected()){
           months = 120;
           }
                else if (months2.isSelected()){
                months = 180;
           }
                        else if (months3.isSelected()){
                        months = 360;
           }
Minor quibble. I would format the code above like this.
Code:
// Get the radio button selected
if (months1.isSelected())
{
     months = 120;
}
else if (months2.isSelected())
{
     months = 180;
}
else if (months3.isSelected())
{
     months = 360;
}
As far as the 1-cent discrepancy between your code and the other calculator, your interest rate is a float, while the other quantities are double. Here's from jButton1ActionPerformed.
Code:
float interest = ((Float.parseFloat(interestRate.getText())/ 12) / 100);
I would change it to the following. That might make a difference.
Code:
double interest = ((Double.parseDouble(interestRate.getText())/ 12) / 100);
The extra bits of precision in a double might make the difference in the calculation of your monthly payment.
 
  • #7
117
3
Minor quibble. I would format the code above like this.
Code:
// Get the radio button selected
if (months1.isSelected())
{
     months = 120;
}
else if (months2.isSelected())
{
     months = 180;
}
else if (months3.isSelected())
{
     months = 360;
}
As far as the 1-cent discrepancy between your code and the other calculator, your interest rate is a float, while the other quantities are double. Here's from jButton1ActionPerformed.
Code:
float interest = ((Float.parseFloat(interestRate.getText())/ 12) / 100);
I would change it to the following. That might make a difference.
Code:
double interest = ((Double.parseDouble(interestRate.getText())/ 12) / 100);
The extra bits of precision in a double might make the difference in the calculation of your monthly payment.
Thank you, Mark44!

I appreciate the formatting advice a lot, my instructor is a stickler for formatting code for readability.

Also, changing the float to a double fixed the discrepancy in the formula. The monthly payment now calculates correctly. I appreciate all of the help. Physics Forum has been an amazing help as always!

One more thing. I would like to catch problems, like if a person puts in a letter instead of a number, how would I catch that. Right now it just throws an error:

Code:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "j"
        at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
        at java.lang.Double.parseDouble(Double.java:510)
        at my.calculator.MortgagePaymentCalculator.jButton1ActionPerformed(MortgagePaymentCalculator.java:228)
        at my.calculator.MortgagePaymentCalculator.access$700(MortgagePaymentCalculator.java:22)
        at my.calculator.MortgagePaymentCalculator$8.actionPerformed(MortgagePaymentCalculator.java:117)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:6263)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
        at java.awt.Component.processEvent(Component.java:6028)
        at java.awt.Container.processEvent(Container.java:2041)
        at java.awt.Component.dispatchEventImpl(Component.java:4630)
        at java.awt.Container.dispatchEventImpl(Container.java:2099)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
        at java.awt.Container.dispatchEventImpl(Container.java:2085)
        at java.awt.Window.dispatchEventImpl(Window.java:2475)
        at java.awt.Component.dispatchEvent(Component.java:4460)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
what would I do and where would I put it in the code?
 
Last edited:
  • #8
33,506
5,192
As you have seen, parseDouble throws NumberFormatException if the string being parsed doesn't actually contain a number.

In your jButton1ActionPerformed handler, you are using the static method, Double.parseDouble(string), and then assigning that value to a variable such as principal.
Code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // On click of calculate button, the monthly payment is calculated
        // and output to the monthly payment text box
        int months = 0;
        double principle = Double.parseDouble(price.getText());
        double payment = Double.parseDouble(downPayment.getText());
        float interest = ((Float.parseFloat(interestRate.getText())/ 12) / 100);
        double loan = (principle - payment);
        .
        .
        .
If the text entered by the user contains non-numeric characters, parseDouble throws. If you can guarantee that the text really contains numeric data only, parseDouble should not have a problem.

One way to make sure that the text field contains appropriate data is to check it when the user types it in, in each of the handlers for text entry. One of them is shown below, but you'll need to do the same sort of thing in the handlers for payment and interest.

Code:
private void priceActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // User enters total price of home to be bought
        
}
You don't show any code in the above handler, so this doesn't seem to be your final code. I imagine that you are using the Scanner class to do input. If so, hasNextDouble returns true if the input stream contains a number that can be interpreted as a double.
 
  • #9
117
3
As you have seen, parseDouble throws NumberFormatException if the string being parsed doesn't actually contain a number.


One way to make sure that the text field contains appropriate data is to check it when the user types it in, in each of the handlers for text entry. One of them is shown below, but you'll need to do the same sort of thing in the handlers for payment and interest.

Code:
private void priceActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // User enters total price of home to be bought
        
}
You don't show any code in the above handler, so this doesn't seem to be your final code. I imagine that you are using the Scanner class to do input. If so, hasNextDouble returns true if the input stream contains a number that can be interpreted as a double.
I had originally implemented the scanner class, but it didn't seem to be doing anything so i took it out. The program actually has no scanner class, LOL. I am not sure how that works, but it does. Each one of the handlers for the text fields had a scanner input method, but, like I said, upon implementation, it worked without them, so I figured it was unnecessary code and removed all the scanner info.

What I am thinking is that I need a catch in the following place (and the other two handlers as well):

Code:
private void priceActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // User enters total price of home to be bought

      **SOME CODE TO CATCH INCORRECT INPUT SUCH AS LETTER GOES HERE**
        
    }
 
  • #10
33,506
5,192
OK, maybe something like this:
Code:
try
{
   double payment = Double.parseDouble(downPayment.getText());
}
catch (NumberFormatException nfe)
{
   // Code to inform the user of bad input.
}
 

Related Threads on Java GUI Mortgage Calculator

Replies
27
Views
21K
  • Last Post
Replies
5
Views
3K
Replies
2
Views
1K
Replies
0
Views
3K
Replies
7
Views
3K
Replies
3
Views
5K
Replies
0
Views
790
Top