[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

GUI Mortgage Calculator

Posted on 2011-04-28
6
Medium Priority
?
792 Views
Last Modified: 2012-05-11
Good Afternoon,

Im trying to get my GUI calculator to display on the JFrame instead of the option windows so that way each it is all on one window so as to input the three different variables.  I have created the Window but left the JOptionPane until I can get a better picture on what I need to do.  Here is the code:
/*
Joshua Gutierrez
University of Phoenix
PRG 421
Week 2 Individual Assignment
Java GUI/Service Request 4*/

import java.text.DecimalFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.JOptionPane;

public class GutierrezMortgageGui extends JFrame
{
public static void main(String[] args)
{
double loanAmount;//Declaring my Variables
double loanInterest;//Declaring my Variables
double monthlyPayment;//Declaring my Variables
double interestRate;
int loanTerm;

//Create the main window
JFrame mainWindow = new JFrame();


//Decimal Format
String totalLoan, interestLoan, termLoan;
DecimalFormat decimalPlaces=new DecimalFormat("0.00"); //Format decimal point for proper display

//Set the window properties
mainWindow.setTitle("Joshua's Mortgage Calculator");
mainWindow.setSize(680,460);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);


//String and JOptionPane to show input dialog
totalLoan=JOptionPane.showInputDialog(null, "Enter the Amount of the Loan: ");
loanAmount = Double.parseDouble(totalLoan); 

interestLoan=JOptionPane.showInputDialog(null, "Enter the Interest Rate of the Loan in decimal Form: ");
loanInterest = Double.parseDouble(interestLoan)/12;
 
termLoan=JOptionPane.showInputDialog(null, "Enter the Term of the Loan: ");
loanTerm = Integer.parseInt(termLoan)*12;

//Mortgage Calculation Formula
monthlyPayment = (loanAmount * loanInterest) / (1 - Math.pow(1 + loanInterest, -loanTerm));

JOptionPane.showMessageDialog(null,"\t\tMonthly Payment is $" + decimalPlaces.format(monthlyPayment));
System.exit(0);
}}

Open in new window


Thank you for any help you can assist me with.  I am very much a newbie to this stuff.
0
Comment
Question by:PapaDragonX
  • 4
  • 2
6 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35487079

You can look at this MortgageCacluclator

// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;


import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

import java.text.DecimalFormat;   //For display the monthly payments as money

import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;



// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

      static  String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
      static String [] toReplace;
         DecimalFormat money = new DecimalFormat("$###,###.00");

   // Define the JPanel where we will draw and place all of our components.
    JPanel contentPanel = null;

    // GUI elements to display labels, fields, table, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    JLabel years_label = null;
    JTextField years_text = null;

    JLabel rate_label = null;
    JTextField rate_text = null;

    JLabel choose_label = null;
    JComboBox choose_combo = null;

    JRadioButton rbutton01 = null;
    JRadioButton rbutton02 = null;

    ButtonGroup buttongroup = null;

    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table with scroll pane
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int numberOfLinesGenerated=1;
        int number_years; //term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment;  // monthly payment for mortgage
        double monthly_interest_rate ; // monthly interest
        int number_of_months; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 20, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 27));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 65, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 65, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            rbutton01 = new JRadioButton();
            rbutton01.setText("Get values from file Or");
            rbutton01.setBounds(90, 95, 220, 25);
            //sets the font size and font
            rbutton01.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton01.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton01);

            rbutton02 = new JRadioButton();
            rbutton02.setText("Choose Values");
            rbutton02.setBounds(350, 95, 220, 25);
            //sets the font size and font
            rbutton02.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton02.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton02);

            buttongroup = new ButtonGroup();
            buttongroup.add(rbutton01);
            buttongroup.add(rbutton02);

             //Number of Years Label
            years_label = new JLabel();
             //This will align the label right
            years_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            years_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            years_label.setText("Number of Years for Mortgage : ");
             //sets the font size and font
            years_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            years_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(years_label);

            //Number of Years Text Field
            years_text = new JTextField();
            // Set the boundary of this text field
            years_text.setBounds(350, 125, 160, 25);
            //sets what it entered in text field
            years_text.setText(Integer.toString(number_years));
            contentPanel.add(years_text);

            //Annual Interest Rate Label
            rate_label = new JLabel();
            //This will align the label right
            rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            rate_label.setBounds(90, 165, 220, 25);
            // Sets the label text
            rate_label.setText("Annunal Interest Rate : ");
             //sets the font size and font
            rate_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            rate_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rate_label);

            //Annual Interest Rate  Text Field
            rate_text = new JTextField();
            // Set the boundary of this text field
            rate_text.setBounds(350, 165, 160, 25);
            //sets what it entered in text field
            rate_text.setText(Double.toString(interest_rate * 100) + "%");
            //Adds it to the contentPanel
            contentPanel.add(rate_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);

                    toReplace = new String[4];
            toReplace[0] =  "Select Mortgage";
            try{
            DataInputStream in = new DataInputStream(new FileInputStream("InterestRate-Term.txt"));
                String buff = null;
                int count = 1;
                while((buff = in.readLine()) != null){
                    StringTokenizer t = new StringTokenizer(buff,",");
                    String perc = t.nextToken().trim();
                    String yrs = t.nextToken().trim();
                    toReplace[count] = yrs + " years at " + perc + "%";
                    count++;


                }
                  in.close();

            } catch(Exception ex){
                System.out.println(ex.toString());
                ex.printStackTrace();
            }


            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 200, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 200, 90, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);


             rbutton01.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    if(rbutton01.isSelected()){
                        System.out.println("one button clicke");
                        contentPanel.removeAll();
                        contentPanel.add(principal_label);
                        contentPanel.add(principal_text);

                        contentPanel.add(rbutton01);
                        contentPanel.add(rbutton02);

                               choose_combo.removeAllItems();
                   for(int jj=0; jj<4; jj++){
                       choose_combo.addItem(MortgageCalculator.toReplace[jj]);

                   }
                        contentPanel.add(choose_label);
                          contentPanel.add(choose_combo);

                        contentPanel.add(years_label);
                        contentPanel.add(years_text);

                        contentPanel.add(rate_label);
                        contentPanel.add(rate_text);

                        contentPanel.add(btnCalculate);
                        contentPanel.add(btnReset);

                        setVisible(true);
                      }
                    }
             });

            rbutton02.setSelected(true);


            rbutton02.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
               if(rbutton02.isSelected()){
                       System.out.println(" button two clicke");
                   contentPanel.removeAll();
                    contentPanel.add(principal_label);
                    contentPanel.add(principal_text);

                    contentPanel.add(rbutton01);
                    contentPanel.add(rbutton02);

                    choose_combo.removeAllItems();
                   for(int jj=0; jj<4; jj++){
                       choose_combo.addItem(MortgageCalculator.mortgage[jj]);
                   }

                    contentPanel.add(choose_label);
                    contentPanel.add(choose_combo);

                    contentPanel.add(btnCalculate);
                    contentPanel.add(btnReset);

                    setVisible(true);
                  }
                }
            });


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

           // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fiedl and the combo box,
            // Calcutes the montly payment adds to result text area
            //and adds it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the field
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());

                 if(rbutton01.isSelected())
	{
		try
		{

                StreamTokenizer st=new StreamTokenizer(new BufferedReader(new FileReader("InterestRate-Term.txt")));
                int linecount=0;
                    while(st.nextToken()!=StreamTokenizer.TT_EOF)
                    {
			if(st.lineno() ==numberOfLinesGenerated)
			{
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			number_years =(int) st.nval;
			years_text.setText(""+st.nval);
			st.nextToken();
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			interest_rate= st.nval;
			rate_text.setText(""+st.nval);

			break;
			}
			System.out.println (st.lineno())				;
		}

                    }catch (Exception addException){//Catch exception if any
                    JOptionPane.showMessageDialog(null, "Error While reading Loandata file\n" +  addException);
                }

                }
                  else
                if(rbutton02.isSelected())
                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }
                 }
                    //calculates the number of months for mortgage
                    //This determines the number of payments to be made
                    number_of_months = number_years * 12;

                    //caluclates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Calculates the monthly payment for mortgage
                    monthly_payment = (principal* monthly_interest_rate)/(1 - Math.pow(1 + monthly_interest_rate, -number_of_months));


                   // Sets the result text
                    result.setText("Loan Amount = " + money.format(principal)
                    +"\nInterest Rate = " + (interest_rate * 100) +"%"+"\nLength of Loan = "
                    + Math.round(number_years * 12.0) + " months"+"\nMonthly Payment = "
                    + money.format(monthly_payment)); //calling the monthly_payment

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());
        }

        return contentPanel;
    }




    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    public MyDTableModel getModel() {
        String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};

        model = null;
        model = new MyDTableModel();
        for (int i = 0; i < 6; i++) {
            model.addColumn(columnNames[i]);
        }

        // This is the necessary data to calculate the table
        if (principal > 0 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < number_of_months; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    public double getPercent(String val) {
        boolean isPercent = false;
        double value = 0;
        try {
            if (val.indexOf('%') > -1) {
                value = NumberFormat.getPercentInstance().parse(val).doubleValue();
                isPercent = true;
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }

        // Have a percentage already in decimal format
        if(!isPercent)
            value = value/100.0;

        return value;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        result.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MortgageCalculator thisClass = new MortgageCalculator();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    class MyDTableModel extends DefaultTableModel {

        public Class<? extends Object> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    //This class adds the table to the JFrame
    class MyJTable extends JTable {

        public MyJTable(){
            super();
        }

        public MyJTable(DefaultTableModel m){
            super(m);

        }

    }
}

Open in new window

0
 

Author Comment

by:PapaDragonX
ID: 35488905
Thanks for the help, however, this calculator is beyond what I need to complete.  I am confused more by looking at the hundreds of lines of code.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35488932
I just commented out many lines from it.
maybe you'll look once again.

Remove all commented lines it will
not be so iintimidating.

If you want to display it on the JFrame,
that's more or less waht you need.

look at it, I can remove say radioboxes
from it - you'll just have pricipal and dropdown

Let me know, what else you want to remove
- everything else, I think  is necessary

Just compile and excute it:

// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;


import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

import java.text.DecimalFormat;   //For display the monthly payments as money

import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;



// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

      static  String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
      static String [] toReplace;
         DecimalFormat money = new DecimalFormat("$###,###.00");

   // Define the JPanel where we will draw and place all of our components.
    JPanel contentPanel = null;

    // GUI elements to display labels, fields, table, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    JLabel years_label = null;
    JTextField years_text = null;

    JLabel rate_label = null;
    JTextField rate_text = null;

    JLabel choose_label = null;
    JComboBox choose_combo = null;

    JRadioButton rbutton01 = null;
    JRadioButton rbutton02 = null;

    ButtonGroup buttongroup = null;

    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table with scroll pane
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int numberOfLinesGenerated=1;
        int number_years; //term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment;  // monthly payment for mortgage
        double monthly_interest_rate ; // monthly interest
        int number_of_months; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 20, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 27));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 65, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 65, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

            rbutton01 = new JRadioButton();
            rbutton01.setText("Values from file");
            rbutton01.setBounds(90, 95, 220, 25);
            //sets the font size and font
            rbutton01.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton01.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton01);

            rbutton02 = new JRadioButton();
            rbutton02.setText("Values from array");
            rbutton02.setBounds(350, 95, 220, 25);
            //sets the font size and font
            rbutton02.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            rbutton02.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(rbutton02);

            buttongroup = new ButtonGroup();
            buttongroup.add(rbutton01);
            buttongroup.add(rbutton02);
            rbutton02.setSelected(true);

             //Number of Years Label
            years_label = new JLabel();
             //This will align the label right
            years_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            years_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            years_label.setText("Number of Years for Mortgage : ");
             //sets the font size and font
            years_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            years_label.setForeground(Color.white);
            //Adds it to the contentPanel
       //     contentPanel.add(years_label);

            //Number of Years Text Field
            years_text = new JTextField();
            // Set the boundary of this text field
            years_text.setBounds(350, 125, 160, 25);
            //sets what it entered in text field
            years_text.setText(Integer.toString(number_years));
       //     contentPanel.add(years_text);

            //Annual Interest Rate Label
            rate_label = new JLabel();
            //This will align the label right
            rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            rate_label.setBounds(90, 165, 220, 25);
            // Sets the label text
            rate_label.setText("Annunal Interest Rate : ");
             //sets the font size and font
            rate_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            rate_label.setForeground(Color.white);
            //Adds it to the contentPanel
        //    contentPanel.add(rate_label);

            //Annual Interest Rate  Text Field
            rate_text = new JTextField();
            // Set the boundary of this text field
            rate_text.setBounds(350, 165, 160, 25);
            //sets what it entered in text field
            rate_text.setText(Double.toString(interest_rate * 100) + "%");
            //Adds it to the contentPanel
       //     contentPanel.add(rate_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);

                    toReplace = new String[4];
            toReplace[0] =  "Select Mortgage";
            try{
            DataInputStream in = new DataInputStream(new FileInputStream("InterestRate-Term.txt"));
                String buff = null;
                int count = 1;
                while((buff = in.readLine()) != null){
                    StringTokenizer t = new StringTokenizer(buff,",");
                    String perc = t.nextToken().trim();
                    String yrs = t.nextToken().trim();
                    toReplace[count] = yrs + " years at " + perc + "%";
                    count++;


                }
                  in.close();

            } catch(Exception ex){
                System.out.println(ex.toString());
                ex.printStackTrace();
            }


            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 200, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 200, 90, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);


             rbutton01.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    if(rbutton01.isSelected()){
                        System.out.println("one button clicke");
                      //  contentPanel.removeAll();
                      //  contentPanel.add(principal_label);
                      //  contentPanel.add(principal_text);

                      //  contentPanel.add(rbutton01);
                      //  contentPanel.add(rbutton02);

                               choose_combo.removeAllItems();
                   for(int jj=0; jj<4; jj++){
                       choose_combo.addItem(MortgageCalculator.toReplace[jj]);

                   }
                        contentPanel.add(choose_label);
                          contentPanel.add(choose_combo);

                   //     contentPanel.add(years_label);
                   //     contentPanel.add(years_text);

                  //      contentPanel.add(rate_label);
                 //       contentPanel.add(rate_text);

                      //  contentPanel.add(btnCalculate);
                      //  contentPanel.add(btnReset);

                      //  setVisible(true);
                      }
                    }
             });

           // rbutton02.setSelected(true);


            rbutton02.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
               if(rbutton02.isSelected()){
                       System.out.println(" button two clicke");
                 //  contentPanel.removeAll();
                 //   contentPanel.add(principal_label);
                 //   contentPanel.add(principal_text);

                   // contentPanel.add(rbutton01);
                   // contentPanel.add(rbutton02);

                    choose_combo.removeAllItems();
                   for(int jj=0; jj<4; jj++){
                       choose_combo.addItem(MortgageCalculator.mortgage[jj]);
                   }

                  //  contentPanel.add(choose_label);
                  //  contentPanel.add(choose_combo);

                  //  contentPanel.add(btnCalculate);
                  //  contentPanel.add(btnReset);

                  //  setVisible(true);
                  }
                }
            });


            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

           // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fiedl and the combo box,
            // Calcutes the montly payment adds to result text area
            //and adds it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the field
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());
                      /*
                 if(rbutton01.isSelected())
	{
		try
		{

                StreamTokenizer st=new StreamTokenizer(new BufferedReader(new FileReader("InterestRate-Term.txt")));
                int linecount=0;
                    while(st.nextToken()!=StreamTokenizer.TT_EOF)
                    {
			if(st.lineno() ==numberOfLinesGenerated)
			{
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			number_years =(int) st.nval;
			years_text.setText(""+st.nval);
			st.nextToken();
			if(st.ttype==StreamTokenizer.TT_NUMBER)
			interest_rate= st.nval;
			rate_text.setText(""+st.nval);

			break;
			}
			System.out.println (st.lineno())				;
		}

                    }catch (Exception addException){//Catch exception if any
                    JOptionPane.showMessageDialog(null, "Error While reading Loandata file\n" +  addException);
                }

                }
                  else
                if(rbutton02.isSelected())
                */
                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }
                 }
                    //calculates the number of months for mortgage
                    //This determines the number of payments to be made
                    number_of_months = number_years * 12;

                    //caluclates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Calculates the monthly payment for mortgage
                    monthly_payment = (principal* monthly_interest_rate)/(1 - Math.pow(1 + monthly_interest_rate, -number_of_months));


                   // Sets the result text
                    result.setText("Loan Amount = " + money.format(principal)
                    +"\nInterest Rate = " + (interest_rate * 100) +"%"+"\nLength of Loan = "
                    + Math.round(number_years * 12.0) + " months"+"\nMonthly Payment = "
                    + money.format(monthly_payment)); //calling the monthly_payment

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());
        }

        return contentPanel;
    }




    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    public MyDTableModel getModel() {
        String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};

        model = null;
        model = new MyDTableModel();
        for (int i = 0; i < 6; i++) {
            model.addColumn(columnNames[i]);
        }

        // This is the necessary data to calculate the table
        if (principal > 0 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < number_of_months; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    public double getPercent(String val) {
        boolean isPercent = false;
        double value = 0;
        try {
            if (val.indexOf('%') > -1) {
                value = NumberFormat.getPercentInstance().parse(val).doubleValue();
                isPercent = true;
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }

        // Have a percentage already in decimal format
        if(!isPercent)
            value = value/100.0;

        return value;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        result.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MortgageCalculator thisClass = new MortgageCalculator();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    class MyDTableModel extends DefaultTableModel {

        public Class<? extends Object> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    //This class adds the table to the JFrame
    class MyJTable extends JTable {

        public MyJTable(){
            super();
        }

        public MyJTable(DefaultTableModel m){
            super(m);

        }

    }
}

Open in new window


0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 35489019
Look, I simplified and removed a lot of code.
You cant' go any  simpler with Mortgage Caclulator with GUI.
Look at it and let me know if you have any questions - I'll
try to explain.

And look how nice it looks - it will be the best calculator in your class!

// Importing Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;


import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

import java.text.DecimalFormat;   //For display the monthly payments as money




// Create Mortgage Payment Class
public class MortgageCalculator extends JFrame {

      static  String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
      static String [] toReplace;
         DecimalFormat money = new DecimalFormat("$###,###.00");

   // Define the JPanel where we will draw and place all of our components.
    JPanel contentPanel = null;

    // GUI elements to display labels, fields, table, scoll pane for current information
    JLabel main_title = null;

    JLabel principal_label = null;
    JTextField principal_text = null;

    JLabel years_label = null;
    JTextField years_text = null;

    JLabel rate_label = null;
    JTextField rate_text = null;

    JLabel choose_label = null;
    JComboBox choose_combo = null;

    JRadioButton rbutton01 = null;
    JRadioButton rbutton02 = null;

    ButtonGroup buttongroup = null;

    //GUI text area for results with scroll pane
    JTextArea result = null;
    JScrollPane scrolling_result = null;

    //GUI for Table with scroll pane
    MyJTable total_amounts = null;
    JScrollPane scrolling_table = null;
    MyDTableModel model;

    // creates the button for calculation of the mortgage payments
    JButton btnCalculate = null;
    // Creates a button for reset button
    JButton btnReset = null;

     // Declaration of variables

        int numberOfLinesGenerated=1;
        int number_years; //term mortgage
        double principal; // amount borrowed
        double interest_rate;  // interest for mortgage
        double monthly_payment;  // monthly payment for mortgage
        double monthly_interest_rate ; // monthly interest
        int number_of_months; // number of months for mortgage payments
        double interest_paid; //interest amount added for each month
        double principal_paid;


     //This is the class constructor - initialize the components

    public MortgageCalculator() {
        super();
        initialize();
    }

    public void initialize() {
        // Defines the window size of 600px by 500 px
        this.setSize(700, 600);
        // The JPanel is where all the components are places.
        this.setContentPane(getJPanel());
        // Define the title of the window.
        this.setTitle("McBride Financial Services Mortgage Calculator");
    }

    public JPanel getJPanel() {
        if (contentPanel == null) {
            // initializes the contentPanel
            contentPanel = new JPanel();
            // Set the Panel to null to put the components into the panel
            contentPanel.setLayout(null);

            contentPanel.setBackground(new Color(38,44,125));

            // GUI elements to display labels and fields for current information

            // Main Title of the Calculator
            main_title = new JLabel();
            //This will center the label
            main_title.setHorizontalAlignment(SwingConstants.CENTER);
            // Set the boundary of this label
            main_title.setBounds(200, 20, 300, 30);
            // Sets the title to application
            main_title.setText("Mortgage Calculator");
            //sets the font size and font
            main_title.setFont(new Font("Serif", Font.PLAIN, 27));
           //sets the font color
            main_title.setForeground(Color.white);

            // Add the Title to the  contentPanel
            contentPanel.add(main_title);

            //Principal Label
            principal_label = new JLabel();
            //This will align the label right
            principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Set the boundary of this label
            principal_label.setBounds(90, 65, 220, 25);
            // Sets the label text
            principal_label.setText("Mortgage Principal : ");
            //sets the font size and font
            principal_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
            //sets the font color
            principal_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(principal_label);

            //Principal Text Field
            principal_text = new JTextField();
            // Set the boundary of this text field
            principal_text.setBounds(350, 65, 160, 25);
            //sets what it entered in text field
            principal_text.setText(Double.toString(principal));
            //Adds it to the contentPanel
            contentPanel.add(principal_text);

             //Number of Years Label
            years_label = new JLabel();
             //This will align the label right
            years_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            years_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            years_label.setText("Number of Years for Mortgage : ");
             //sets the font size and font
            years_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            years_label.setForeground(Color.white);
            //Adds it to the contentPanel
       //     contentPanel.add(years_label);

            //Number of Years Text Field
            years_text = new JTextField();
            // Set the boundary of this text field
            years_text.setBounds(350, 125, 160, 25);
            //sets what it entered in text field
            years_text.setText(Integer.toString(number_years));
       //     contentPanel.add(years_text);

            //Annual Interest Rate Label
            rate_label = new JLabel();
            //This will align the label right
            rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            rate_label.setBounds(90, 165, 220, 25);
            // Sets the label text
            rate_label.setText("Annunal Interest Rate : ");
             //sets the font size and font
            rate_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            rate_label.setForeground(Color.white);
            //Adds it to the contentPanel
        //    contentPanel.add(rate_label);

            //Annual Interest Rate  Text Field
            rate_text = new JTextField();
            // Set the boundary of this text field
            rate_text.setBounds(350, 165, 160, 25);
            //sets what it entered in text field
            rate_text.setText(Double.toString(interest_rate * 100) + "%");
            //Adds it to the contentPanel
       //     contentPanel.add(rate_text);

            choose_label = new JLabel();
            //This will align the label right
            choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
            // Sets the boundary of this label
            choose_label.setBounds(90, 125, 220, 25);
            // Sets the label text
            choose_label.setText("Choose Mortgage Plan : ");
             //sets the font size and font
            choose_label.setFont(new Font("Sans Serif", Font.BOLD, 14));
             //sets the font color
            choose_label.setForeground(Color.white);
            //Adds it to the contentPanel
            contentPanel.add(choose_label);


            String mortgage[] = {"Select Mortgage","10 years at 5.35%","20 years at 5.5%","30 years at 5.75%"};
            choose_combo = new JComboBox(mortgage);
            choose_combo.setBounds(350, 125, 180, 30);
            contentPanel.add(choose_combo);

            //Text Area for result
            result = new JTextArea(5, 20);
            result.setBounds(170, 250, 350, 75);
            scrolling_result = new JScrollPane(result);
            contentPanel.add(result);

            //Table for calculations
            total_amounts = new MyJTable();
            scrolling_table = new JScrollPane (total_amounts);
            scrolling_table.setBounds(20, 350, 650, 200);
            contentPanel.add(scrolling_table);


            // Creates a button for reset button
            btnReset = new JButton ();
            btnReset.setBounds(355, 200, 90, 30);
            btnReset.setText("Reset");
            contentPanel.add(btnReset);


            // creates the button for calculation of the mortgage payments
            btnCalculate = new JButton ();
            btnCalculate.setBounds(245, 200, 90, 30);
            btnCalculate.setText("Calculate");
            contentPanel.add(btnCalculate);




            // Adds the action listerner to  the reset button
            btnReset.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                // Calls the onButtonReset() method
                onButtonReset();
                 }
            });

           // This is the main area that when the calculate button is pressed,
            // will grab the values from the text fiedl and the combo box,
            // Calcutes the montly payment adds to result text area
            //and adds it to the table.
            btnCalculate.addActionListener(new ActionListener() {
                // Get the values for each of the field
                public void actionPerformed(ActionEvent e) {
                  principal=getDouble(principal_text.getText());

                    {
                //Gets the values from the combo box
                String str = (String)choose_combo.getSelectedItem();
                if(str.equals("10 years at 5.35%"))
                    {
                        interest_rate = 0.0535;
                        number_years = 10;
                    }
                else
                if(str.equals("20 years at 5.5%"))
                    {
                        interest_rate = 0.055;
                        number_years = 20;
                    }
                else
                if(str.equals("30 years at 5.75%"))
                {
                    interest_rate = 0.0575;
                    number_years = 30;
                }
                 }
                    //calculates the number of months for mortgage
                    //This determines the number of payments to be made
                    number_of_months = number_years * 12;

                    //caluclates the monthly interest rate
                    monthly_interest_rate = interest_rate/12.0;

                    //Calculates the monthly payment for mortgage
                    monthly_payment = (principal* monthly_interest_rate)/(1 - Math.pow(1 + monthly_interest_rate, -number_of_months));


                   // Sets the result text
                    result.setText("Loan Amount = " + money.format(principal)
                    +"\nInterest Rate = " + (interest_rate * 100) +"%"+"\nLength of Loan = "
                    + Math.round(number_years * 12.0) + " months"+"\nMonthly Payment = "
                    + money.format(monthly_payment)); //calling the monthly_payment

                    // Have the necessary information for the model lets recalculate it.
                    if(total_amounts != null){
                        total_amounts.setModel(getModel());
                    }

                }
            });
            //Adds the calculate button
            contentPanel.add(btnCalculate);

            //Adds the scroll pane
            contentPanel.add(getScrollPane());
        }

        return contentPanel;
    }




    // This the Scroll pane for the table - sets the boundary
    public JScrollPane getScrollPane() {
        if (scrolling_table == null) {
            scrolling_table = new JScrollPane();
            scrolling_table.setBounds(65, 225, 425, 120);
            scrolling_table.setViewportView(getTable());
        }
        return scrolling_table;
    }

    public JTable getTable() {
        if (total_amounts == null) {
                total_amounts = new MyJTable(getModel());
        }
        return total_amounts;
    }

    //this will calculate the model for the table over and over again.
    public MyDTableModel getModel() {
        String[] columnNames = {"Payment Number", "Begin Balance", "Monthly Payment","Interest Paid","Principal Paid", "Ending Balance"};

        model = null;
        model = new MyDTableModel();
        for (int i = 0; i < 6; i++) {
            model.addColumn(columnNames[i]);
        }

        // This is the necessary data to calculate the table
        if (principal > 0 && interest_rate != 0 && number_years != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < number_of_months; i++) {
                Object data[] = new Object[6];
                 data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthly_payment);
                data[3] = nf.format(interest_paid = principal * monthly_interest_rate);
                data[4] = nf.format(principal_paid = monthly_payment - interest_paid);
                data[5] = nf.format(principal = principal - principal_paid);
                new_principal = principal;

                model.addRow(data);
            }
        }
        return model;
    }

    /**
     * The following will parse a double value from entered string
     * If the number is entered with a dollar sign, than parse it
     * one way otherwise parse it using the default number.
     * If there is an error, then zero will be returned
     * @return value
     */
    public double getDouble(String val) {
        double value = 00;
        try {
            // this tests to see if there is a dollar sign, if there
            // is it uses the currency number formater, otherwise just
            // the number formatter.
            if (val.indexOf('$') > -1) {
                // we need to use the currency expression
                value = NumberFormat.getCurrencyInstance().parse(val).doubleValue();
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            // Generates an error here, can add a JOptionDialog to display the
            // text and the error
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }

    /**
     * The following will parse a string with a percent or no percent sign, and then divide it to decimal format.
     * @param val
     * @return
     */
    public double getPercent(String val) {
        boolean isPercent = false;
        double value = 0;
        try {
            if (val.indexOf('%') > -1) {
                value = NumberFormat.getPercentInstance().parse(val).doubleValue();
                isPercent = true;
            } else {
                value = NumberFormat.getNumberInstance().parse(val).doubleValue();
            }
        } catch (java.text.ParseException e) {
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }

        // Have a percentage already in decimal format
        if(!isPercent)
            value = value/100.0;

        return value;
    }

      // Information for  Reset Button
         public void onButtonReset(){

        // Resets the fields
        principal_text.setText("");
        result.setText("");
        total_amounts.setModel(new MyDTableModel());

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // use the Nimbus look and feel if available.
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                MortgageCalculator thisClass = new MortgageCalculator();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    class MyDTableModel extends DefaultTableModel {

        public Class<? extends Object> getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    //This class adds the table to the JFrame
    class MyJTable extends JTable {

        public MyJTable(){
            super();
        }

        public MyJTable(DefaultTableModel m){
            super(m);

        }

    }
}

Open in new window


 
VeryMortgageCalculator.PNG
0
 

Author Closing Comment

by:PapaDragonX
ID: 35489125
This solution is a little overboard but it will help me to understand it.  I really only needed just a simple input of the amount, interest rate, term, and then a textbox that gives just the amount per month only.  Thanks for you help.  If you ran my code earlier, that was basically all I needed.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35489360
Well, we still needed to make it in the frame instead of option pane.
This one is really not that far. Look at it, I;m sure you will be happy.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month17 days, 21 hours left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question