7 Replies - 5020 Views - Last Post: 23 May 2011 - 03:57 AM Rate Topic: -----

#1 jkg1981  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 20-May 11

Java GUI Mortgage Amortization

Posted 20 May 2011 - 03:33 PM

Good Afternoon,

I am on my last week of class and I am trying to get my code to display the amortized loan (break-down)in the table I create. I am able to select from a drop down menu or enter a mortgage manually the rate/term to calculate the principle but I cannot get it to display the break-down of the payment.

Here is the code:

/*
Joshua Gutierrez
University of Phoenix
PRG 421
Week 2 Individual Assignment
Java GUI/Service Request 4
Professor Matt Berg
May 2, 2011*/

// Importing Multiple Classes (Some Just In Case They Are Needed)

import java.awt.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JTable;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
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;

public class GutierrezMortgageGui extends JFrame {

	static String mortgage[] = { "Select Mortgage", "30 years at 5.75%", "15 years at 5.5%", "7 years at 5.35%" };
	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, scroll 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 GutierrezMortgageGui() {
		super();
		initialize();
	}

	// Window size, JPanel, setTitle

	public void initialize() {
		this.setSize(700, 700);
		this.setContentPane(getJPanel());
		this.setTitle("Gutierrez Mortgage GUI and McBride Financial");
	}

	public JPanel getJPanel() {
		if (contentPanel == null) {
			contentPanel = new JPanel();
			contentPanel.setLayout(null);
			contentPanel.setBackground(Color.black);

			// GUI elements to display labels and fields for current information
			// to include Alignment, Boundary, Title, Font, Font Size, Color

			// Main Title of the Calculator
			main_title = new JLabel();
			main_title.setHorizontalAlignment(SwingConstants.CENTER);
			main_title.setBounds(130, 20, 400, 30);
			main_title.setText("Loan Amortization Calculator");
			main_title.setFont(new Font("Times New Roman", Font.BOLD, 30));
			main_title.setForeground(Color.white);
			contentPanel.add(main_title);

			// Principal Label
			principal_label = new JLabel();
			principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
			principal_label.setBounds(90, 65, 220, 25);
			principal_label.setText("Mortgage Principle Amount : ");
			principal_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			principal_label.setForeground(Color.white);
			contentPanel.add(principal_label);

			// Principal Text Field Features

			principal_text = new JTextField();
			principal_text.setBounds(350, 65, 160, 25);
			contentPanel.add(principal_text);

			// Mortgage Plan Label

			choose_label = new JLabel();
			choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
			choose_label.setBounds(90, 125, 220, 25);
			choose_label.setText("Select Mortgage Plan : ");
			choose_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			choose_label.setForeground(Color.white);
			contentPanel.add(choose_label);

			// String for Mortgage Variation

			String mortgage[] = { "Select Mortgage", "30 years at 5.75%","15 years at 5.5%", "7 years at 5.35%" };
			choose_combo = new JComboBox(mortgage);
			choose_combo.setBounds(350, 125, 180, 30);
			choose_combo.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
									
					}
			});
			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 amortization calculations
			
         total_amounts = new MyJTable();
         scrolling_table = new JScrollPane (total_amounts);
         scrolling_table.setBounds(25, 400, 650, 200);
         contentPanel.add(scrolling_table);
			
			
			// Number of Years Label
			years_label = new JLabel();
			years_label.setHorizontalAlignment(SwingConstants.RIGHT);
			years_label.setBounds(90, 200, 220, 25);
			years_label.setText("Mortgage Term : ");
			years_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			years_label.setForeground(Color.white);
			contentPanel.add(years_label);

			// Number of Years Text Field
			years_text = new JTextField();
			years_text.setBounds(350, 205, 160, 25);
			contentPanel.add(years_text);

			// Annual Interest Rate Label
			rate_label = new JLabel();
			rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
			rate_label.setBounds(90, 165, 220, 25);
			rate_label.setText("Annual Interest Rate(Decimal) : ");
			rate_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			rate_label.setForeground(Color.white);
			contentPanel.add(rate_label);

			// Annual Interest Rate Text Field
			rate_text = new JTextField();
			rate_text.setBounds(350, 165, 160, 25);
			contentPanel.add(rate_text);

			// Button for reset button

			btnReset = new JButton();
			btnReset.setBounds(355, 350, 110, 30);
			btnReset.setText("Reset");
			contentPanel.add(btnReset);

			// Button for calculation of the mortgage payments

			btnCalculate = new JButton();
			btnCalculate.setBounds(245, 350, 110, 30);
			btnCalculate.setText("Calculate");
			contentPanel.add(btnCalculate);

			// Adds the action listener to the reset button
			
         btnReset.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
           onButtonreset();                 }
            });
           
          btnCalculate.addActionListener(new ActionListener() {
           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("30 years at 5.75%")) {
	        interest_rate = 0.0575;
	        number_years = 30;
		          }
	        else			
           if(str.equals("15 years at 5.5%")) {
           interest_rate = 0.055;
           number_years = 15;
                    }
           else
           if(str.equals("7 years at 5.35%")) {
           interest_rate = 0.0535;
           number_years = 15;
                }
                 }                    
					  
			 //Calculates the number of months for mortgage
			 
                    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;
    }
	 
	 

   
    public double getDouble(String val) {
        double value = 00;
        try {
            // This tests to see if there is a dollar sign
            if (val.indexOf('$') > -1) {
                
                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 error
            
            JOptionPane.showMessageDialog(this, "There is an error " + val + ". Please check your entry", "Data Entry Error", JOptionPane.ERROR_MESSAGE);
        }
        return value;
    }
	 
	 

    
    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());

    }

   
    public static void main(String[] args) {

        // Using Nimbus "Look and Feel" to make the layout more appealing.
        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() {
                GutierrezMortgageGui thisClass = new GutierrezMortgageGui();
                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);

        }

    }
}


Is This A Good Question/Topic? 0
  • +

Replies To: Java GUI Mortgage Amortization

#2 jkg1981  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 20-May 11

Re: Java GUI Mortgage Amortization

Posted 20 May 2011 - 06:42 PM

I fixed it. Thanks for your help!
Was This Post Helpful? 0
  • +
  • -

#3 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10466
  • View blog
  • Posts: 38,785
  • Joined: 27-December 08

Re: Java GUI Mortgage Amortization

Posted 21 May 2011 - 09:49 PM

Out of curiosity, would you mind sharing your solution? :)
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Java GUI Mortgage Amortization

Posted 22 May 2011 - 05:29 AM

// Importing Multiple Classes (Some Just In Case They Are Needed)

import java.awt.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JTable;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
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;


If it is the case better to

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

makes the code a lot easier to read and prevent the idea that a class was imported because effectively required
Was This Post Helpful? 1
  • +
  • -

#5 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2871
  • View blog
  • Posts: 11,026
  • Joined: 15-July 08

Re: Java GUI Mortgage Amortization

Posted 22 May 2011 - 08:19 AM

In all my programming jobs thus far, pbl, I have been told to use the extended syntax and explicitly import every class that I use.

Quote

makes the code a lot easier to read and prevent the idea that a class was imported because effectively required


But the point is that I have to say why every class I used was needed. It's a matter of style I guess and varies from employer to employer.
Was This Post Helpful? 1
  • +
  • -

#6 jkg1981  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 20-May 11

Re: Java GUI Mortgage Amortization

Posted 22 May 2011 - 10:00 AM

Here is my solution. Now I am onto trying to make a chart. Been lost with that one for several days now. Thanks!

/*
Joshua Gutierrez
University of Phoenix
PRG 421
Week 5 Individual Assignment
Java GUI/Service Request 7
Professor Matt Berg
May 23, 2011*/

// Importing Multiple Classes (Some Just In Case They Are Needed)

import java.awt.*;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.geom.*;
import java.awt.Container;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JTable;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
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;

public class GutierrezMortgageGui extends JFrame {

	static String mortgage[] = { "Select Mortgage", "30 years at 5.75%", "15 years at 5.5%", "7 years at 5.35%" };
	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, scroll 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 GutierrezMortgageGui() {
		super();
		initialize();
	}

	// Window size, JPanel, setTitle

	public void initialize() {
		this.setSize(720, 730);
		this.setContentPane(getJPanel());
		this.setTitle("Gutierrez Mortgage GUI and McBride Financial");
	}

	public JPanel getJPanel() {
		if (contentPanel == null) {
			contentPanel = new JPanel();
			contentPanel.setLayout(null);
			contentPanel.setBackground(Color.black);

			// GUI elements to display labels and fields for current information
			// to include Alignment, Boundary, Title, Font, Font Size, Color

			// Main Title of the Calculator
			main_title = new JLabel();
			main_title.setHorizontalAlignment(SwingConstants.CENTER);
			main_title.setBounds(130, 20, 400, 30);
			main_title.setText("Loan Amortization Calculator");
			main_title.setFont(new Font("Times New Roman", Font.BOLD, 30));
			main_title.setForeground(Color.white);
			contentPanel.add(main_title);

			// Principal Label
			principal_label = new JLabel();
			principal_label.setHorizontalAlignment(SwingConstants.RIGHT);
			principal_label.setBounds(90, 65, 220, 25);
			principal_label.setText("Mortgage Principle Amount : ");
			principal_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			principal_label.setForeground(Color.white);
			contentPanel.add(principal_label);

			// Principal Text Field Features

			principal_text = new JTextField();
			principal_text.setBounds(350, 65, 160, 25);
			contentPanel.add(principal_text);

			// Mortgage Plan Label

			choose_label = new JLabel();
			choose_label.setHorizontalAlignment(SwingConstants.RIGHT);
			choose_label.setBounds(90, 125, 220, 25);
			choose_label.setText("Select Mortgage Plan : ");
			choose_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			choose_label.setForeground(Color.white);
			contentPanel.add(choose_label);

			// String for Mortgage Variation

			String mortgage[] = { "Select Mortgage", "30 years at 5.75%","15 years at 5.5%", "7 years at 5.35%" };
			choose_combo = new JComboBox(mortgage);
			choose_combo.setBounds(350, 125, 180, 30);
			choose_combo.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					setMortgage();
				}
			});
			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 amortization calculations
			
         total_amounts = new MyJTable();
         scrolling_table = new JScrollPane (total_amounts);
         scrolling_table.setBounds(25, 450, 650, 200);
         contentPanel.add(scrolling_table);
			
			
			// Number of Years Label
			years_label = new JLabel();
			years_label.setHorizontalAlignment(SwingConstants.RIGHT);
			years_label.setBounds(90, 200, 220, 25);
			years_label.setText("Mortgage Term : ");
			years_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			years_label.setForeground(Color.white);
			contentPanel.add(years_label);

			// Number of Years Text Field
			years_text = new JTextField();
			years_text.setBounds(350, 205, 160, 25);
			contentPanel.add(years_text);

			// Annual Interest Rate Label
			rate_label = new JLabel();
			rate_label.setHorizontalAlignment(SwingConstants.RIGHT);
			rate_label.setBounds(90, 165, 220, 25);
			rate_label.setText("Annual Interest Rate(Decimal) : ");
			rate_label.setFont(new Font("Times New Roman", Font.BOLD, 15));
			rate_label.setForeground(Color.white);
			contentPanel.add(rate_label);

			// Annual Interest Rate Text Field
			rate_text = new JTextField();
			rate_text.setBounds(350, 165, 160, 25);
			contentPanel.add(rate_text);

			// Button for reset button

			btnReset = new JButton();
			btnReset.setBounds(355, 350, 110, 30);
			btnReset.setText("Reset");
			contentPanel.add(btnReset);

			// Button for calculation of the mortgage payments

			btnCalculate = new JButton();
			btnCalculate.setBounds(245, 350, 110, 30);
			btnCalculate.setText("Calculate");
			contentPanel.add(btnCalculate);

			// Action listener to the reset button

			btnReset.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					onButtonreset();
				}
			});

			btnCalculate.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					principal=getDouble(principal_text.getText());
					calculate();
				{
			
			//Gets the values from the combo box
			
         String str = (String)choose_combo.getSelectedItem();
           if (str.equals("30 years at 5.75%")) {
	        interest_rate = 0.0575;
	        number_years = 30;
		          }
	        else			
           if(str.equals("15 years at 5.5%")) {
           interest_rate = 0.055;
           number_years = 15;
                    }
           else
           if(str.equals("7 years at 5.35%")) {
           interest_rate = 0.0535;
           number_years = 15;
                }
                 }                    
					  
			 //Calculates the number of months for mortgage
			 
                    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;
    }
			
//setMortgage Calculation//

	public void setMortgage() {
		String str = (String) choose_combo.getSelectedItem();

		if (str.equals("30 years at 5.75%")) {
			rate_text.setText("0.0575");
			years_text.setText("30");
			}
		else			
      if(str.equals("15 years at 5.5%")) {
         rate_text.setText("0.055");
         years_text.setText("15");
                    }
      else
      if(str.equals("7 years at 5.35%")) {
         rate_text.setText("0.0535");
         years_text.setText("7");	
		}

	}

	
// Information for Reset Button//
	
	public void onButtonreset() {
		principal_text.setText("");
		result.setText("");
		rate_text.setText("");
		years_text.setText("");

	}

// Calculate() call//
	
	public void calculate() {	
		double principal = getDouble(principal_text.getText());
		int number_of_years = Integer.parseInt(years_text.getText());
		double interest_rate = getDouble(rate_text.getText());
        if(interest_rate > 1.0)interest_rate = interest_rate/100.0;

		// Calculates the number of months for mortgage so as to determine the number of payments to be made
					
					int number_of_months = number_of_years * 12;

		// Calulates the monthly interest rate
		
					double monthly_interest_rate = interest_rate / 12.0;

		// Equation that calculates the monthly payment for mortgage
		
					double 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_of_years * 12.0)
				+ " months" + "\nMonthly Payment = "
				+ money.format(monthly_payment)); // calling the
													// monthly_payment
	}
	
// This the Scroll pane for the table - sets the boundaries//
    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//
    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;
		  
		
    }
	 
	 public double getDouble(String val) {
		double value = 00;
		try {
			// This tests to see if there is a dollar sign
			if (val.indexOf('$') > -1) {

				value = NumberFormat.getCurrencyInstance().parse(val)
						.doubleValue();
			} else {
				value = NumberFormat.getNumberInstance().parse(val)
						.doubleValue();
			}
		} catch (java.text.ParseException e) {

			// Generates an error here

			JOptionPane.showMessageDialog(this, "There is an error " + val
					+ ". Please check your entry", "Data Entry Error",
					JOptionPane.ERROR_MESSAGE);
		}
		return value;
	}

	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;
	}
	

	 
//main() method//

	public static void main(String[] args) {

		// Using Nimbus "Look and Feel" to make the layout more appealing.
        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() {
                GutierrezMortgageGui thisClass = new GutierrezMortgageGui();
                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);

        }

    }
}//End of Line

Was This Post Helpful? 0
  • +
  • -

#7 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10466
  • View blog
  • Posts: 38,785
  • Joined: 27-December 08

Re: Java GUI Mortgage Amortization

Posted 22 May 2011 - 09:16 PM

You could extend JPanel and override the paint() method. Then use the Graphics param in the paint() method to draw your chart based on the loan data.

class ChartPanel extends JPanel{

    public void paint(Graphics g){
        super.paint(g);
        //use g to draw your chart
    }
}



There are a number of tutorials listed in the Java Game Programming Thread that cover painting. Also, check out the documentation for Graphics as well.

You may also consider using a 3rd Party API like JFreeChart.
Was This Post Helpful? 1
  • +
  • -

#8 jkg1981  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 20-May 11

Re: Java GUI Mortgage Amortization

Posted 23 May 2011 - 03:57 AM

Thanks! I will take a look. It would help if I actually had an instructor that actually instructs!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1