Mortgage Calculator with GUI

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 2664 Views - Last Post: 30 January 2012 - 07:11 AM Rate Topic: -----

#1 thelgar  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 14
  • Joined: 27-January 12

Mortgage Calculator with GUI

Posted 27 January 2012 - 10:10 AM

I am having issues getting my program to populate my comboBox and do calcs based on the new data. Also my graph will not display. i am totally lost and will welcome any help. i keep geting errors saying (in netbeans) expected ;, or illegal start of expression. and the graph just will not load. i know these are small issues but they are the difference between pass and fail. thanks in advance

 

package mortgagecalc;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Canvas;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.*;
import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.border.LineBorder;



public class MortgageCalc extends JFrame {

	String mortgage[] = { "Select Mortgage" };
	//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 mainTitle = null;
	JLabel principalLabel = null;
	JTextField principalText = null;
	JLabel yearsLabel = null;
	JTextField yearsText = null;
	JLabel rateLabel = null;
	JTextField rateText = null;
	JLabel chooseLabel = null;
	JComboBox chooseCombo = null;
	JRadioButton selectionOne = null;
	JRadioButton selectionTwo = null;
	ButtonGroup buttongroup = null;

	// GUI text area for results with scroll pane
	JTextArea result = null;
        JTextArea GraphArea = new JTextArea(19,50);
	JScrollPane scrollingResults = null;

	// GUI for Table with scroll pane
	MyJTable totalAmounts = null;
        JScrollPane scrollingTable = null;
        MyDTableModel model;

	// Creates button for graphing
	JButton graphButton = null;

        // Creates the button for calculation of the mortgage payments
	JButton calculateButton = null;

	// Creates a button for reset button
	JButton resetButton = null;
	
	// Declaration of variables
        int numberOfLinesGenerated=1;
        double numberYears; //term mortgage
        double principal; // amount borrowed
        double rate;  // interest for mortgage
        double monthlyPayment;  // monthly payment for mortgage
        double monthlyRate ; // monthly interest
        double totalMonths; // number of months for mortgage payments
        double interestPaid; //interest amount added for each month
        double principalPaid;

	// This is the class constructor - initialize the components

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

	// Window size, JPanel, setTitle
	public void initialize() {
		this.setSize(720, 670);
		this.setContentPane(getJPanel());
		this.setTitle("Mortgage Calculator by Luther Mann");
	}

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

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

			// Main Title of the Calculator
			mainTitle = new JLabel();
			mainTitle.setHorizontalAlignment(SwingConstants.CENTER);
			mainTitle.setBounds(130, 20, 400, 30);
			mainTitle.setText("Luther's Loan Calculator");
			mainTitle.setFont(new Font("Times New Roman", Font.BOLD, 30));
			mainTitle.setForeground(Color.blue);
			contentPanel.add(mainTitle);
                        
                        //Selection button 1
                        selectionOne = new JRadioButton();
                        selectionOne.setHorizontalAlignment(SwingConstants.CENTER);
                        selectionOne.setBounds(125, 65, 160, 15);
                        selectionOne.setText("Preset Loan Terms");
                        selectionOne.setFont(new Font("Times New Roman", Font.BOLD, 15));
                        selectionOne.setForeground(Color.black);
                        selectionOne.setSelected(true);
                        contentPanel.add(selectionOne);
                
                        //Selection Button 2
                        selectionTwo = new JRadioButton();
                        selectionTwo.setHorizontalAlignment(SwingConstants.CENTER);
                        selectionTwo.setBounds(350, 65, 180, 15);
                        selectionTwo.setText("Enter Your Loan Terms");
                        selectionTwo.setFont(new Font("Times New Roman", Font.BOLD, 15));
                        selectionTwo.setForeground(Color.black);
                        contentPanel.add(selectionTwo);

			// Principal Label
			principalLabel = new JLabel();
			principalLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			principalLabel.setBounds(120, 65, 200, 75);
			principalLabel.setText("Mortgage Principle Amount : ");
			principalLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
			principalLabel.setForeground(Color.blue);
			contentPanel.add(principalLabel);

			// Principal Text Field Features
			principalText = new JTextField();
			principalText.setBounds(350, 90, 160, 25);
			contentPanel.add(principalText);

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

			
                        
                        // String for Mortgage Variation
			Mortgage[] mortgage = new mortgage(0);
                        mortgage(0) = {"Select Mortgage"};
                        
                        for (int i = 0; i less than terms.length; i++)
                        {
                    Mortgage[i] = years[i] + “years…” + terms[i] + “%”;
                }
                                                
			chooseCombo = new JComboBox(mortgage);
			chooseCombo.setBounds(350, 125, 180, 30);
			chooseCombo.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					setMortgage();
				}
			});
			contentPanel.add(chooseCombo);
			
			
			// Text Area for result
			result = new JTextArea(5, 20);
                        result.setEditable(false);
			result.setBounds(170, 250, 350, 75);
			scrollingResults = new JScrollPane(result);
			contentPanel.add(result);
			
			//Table for amortization calculations
			totalAmounts = new MyJTable();
			scrollingTable = new JScrollPane (totalAmounts);
			scrollingTable.setBounds(25, 425, 600, 175);
			contentPanel.add(scrollingTable);

			// Number of Years Label
			yearsLabel = new JLabel();
			yearsLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			yearsLabel.setBounds(90, 200, 220, 25);
			yearsLabel.setText("Mortgage Term : ");
			yearsLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
			yearsLabel.setForeground(Color.blue);
                        yearsLabel.setVisible(false);
			contentPanel.add(yearsLabel);

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

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

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

			// Button for Graphing
			graphButton = new JButton();
			graphButton.setBounds(395, 350, 110, 30);
			graphButton.setText("Graph");
			contentPanel.add(graphButton);

			// Button for reset button
			resetButton = new JButton();
			resetButton.setBounds(285, 350, 110, 30);
			resetButton.setText("Reset");
			contentPanel.add(resetButton);

			// Button for calculation of the mortgage payments
			calculateButton = new JButton();
			calculateButton.setBounds(175, 350, 110, 30);
			calculateButton.setText("Calculate");
			contentPanel.add(calculateButton);

			// ---- Radio Button Listeners
                        selectionOne.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
			hideSelectionTwo();
                        }
                        });
                        selectionTwo.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
			
                        // ---- display results 
                	displaySelectionTwo();
			}
                        });

                        
                        // Action listener to the reset button

			resetButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					onButtonreset();
				}
			});
			
			
			graphButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					drawGraph();
				}
			});
			

			calculateButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					principal=getDouble(principalText.getText());
					calculate();
				{
			
			//Gets the values from the combo box or text box
                                    
	if (selectionOne.isSelected()){
            String str = (String)chooseCombo.getSelectedItem();
           if (str.equals("30 years at 5.75%")) {
	        rate = 0.0575;
	        numberYears = 30;
		          }
           else
               if(str.equals("20 years at 5.65%")) {
                   rate = 0.0565;
                   numberYears = 20;
               }
           
            else			
                if(str.equals("10 years at 5%")) {
                    rate = 0.055;
                    numberYears = 10;
                        }
            else
                if(str.equals("7 years at 5.35%")) {
                rate = 0.0535;
                numberYears = 7;
                }
           
        }
        else {
            
                rate = Double.parseDouble(rateText.getText());
                numberYears = Double.parseDouble(yearsText.getText());
                
                rate = rate/100;
           
           }
         
                 }                    
					  
			 //Calculates the number of months for mortgage
			 
                    totalMonths = numberYears * 12;

          //Caluclates the monthly interest rate
			 
                    monthlyRate = rate/12.0;

          //Calculates the monthly payment for mortgage
			 
                    monthlyPayment = (principal* monthlyRate)/(1 - Math.pow(1 + monthlyRate, -totalMonths));


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

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

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

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

        return contentPanel;
    }
        public void readFile()
        {
          String dataFileName = "/loandata.txt";

		//create arrays to hold values in file
		final ArrayList<Double> rateList = new ArrayList<Double>();
		final ArrayList<Integer> yearList = new ArrayList<Integer>();

		//open and read text file
		try
		{
			BufferedReader br = new BufferedReader(new FileReader(dataFileName));
			String line;

			while ((line = br.readLine()) != null)
			{
				String values[] = line.split(","); //splits each word after comma and stores values in array "values"
				int value1 = Integer.parseInt(values[0]); //sets integer value1 = first word of each line
				double value2 = Double.parseDouble(values[1]); //sets double value2 = second word of each line

				yearList.add(value1); //adds all value1 integers to arraylist
				rateList.add(value2); //adds all value2 doubles to arraylist
			}

			br.close();
		}

		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}

		catch (IOException e)
		{
			e.printStackTrace();
		}  
        }
			
//setMortgage Calculation//

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

		if (str.equals("30 years at 5.75%")) {
			rateText.setText("0.0575");
			yearsText.setText("30");
			}
                else			
                    if(str.equals("20 years at 5.65%")) {
                    rateText.setText("0.0565");
                    yearsText.setText("20");
                    }
		else			
                    if(str.equals("10 years at 5%")) {
                    rateText.setText("0.05");
                    yearsText.setText("10");
                    }
                else
                    if(str.equals("7 years at 5.35%")) {
                    rateText.setText("0.0535");
                    yearsText.setText("7");	
		}
                
            }
               
        

	
// Information for Reset Button//
	
	public void onButtonreset() {
		principalText.setText("");
		rateText.setText("");
		yearsText.setText("");
                result.setText("");
                model.setRowCount(0);
	}

// Calculate() call//
	
	public void calculate() {	
		double principal = getDouble(principalText.getText());
		int number_of_years = Integer.parseInt(yearsText.getText());
		double interest_rate = getDouble(rateText.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)); 
                
                GraphArea.append("" + principalPaid);
													// monthlyPayment
	}
	
// This the Scroll pane for the table - sets the boundaries//
    public JScrollPane getScrollPane() {
        if (scrollingTable == null) {
            scrollingTable = new JScrollPane();
            scrollingTable.setBounds(65, 225, 425, 120);
            scrollingTable.setViewportView(getTable());
        }
        return scrollingTable;
    }

    public JTable getTable() {
        if (totalAmounts == null) {
                totalAmounts = new MyJTable(getModel());
        }
        return totalAmounts;
    }
	 
	
	
//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 && rate != 0 && numberYears != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < totalMonths; i++) {
                Object data[] = new Object[6];
                data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthlyPayment);
                data[3] = nf.format(interestPaid = principal * monthlyRate);
                data[4] = nf.format(principalPaid = monthlyPayment - interestPaid);
                data[5] = nf.format(principal = principal - principalPaid);
                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() {
                MortgageCalc thisClass = new MortgageCalc();
                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);

        }

    }
        
    //used to hide and show the correct components
        public void displaySelectionTwo() {  
        
                chooseCombo.setVisible(false);
		selectionTwo.setSelected(true);
		selectionOne.setSelected(false);
		yearsLabel.setVisible(true);
                yearsLabel.setText("Loan Term Years:    ");
		yearsText.setVisible(true);
                yearsText.setEditable(true);
		rateText.setVisible(true);
                rateText.setEditable(true);
		rateLabel.setVisible(true);
                chooseLabel.setVisible(false);
                rateLabel.setText("Interest Rate     :");
		
        }
        public void hideSelectionTwo() {
		chooseCombo.setVisible(true);
		selectionTwo.setSelected(false);
		selectionOne.setSelected(true);
		principalLabel.setText("Please Select Loan:   ");
		rateLabel.setVisible(false);
		yearsLabel.setText("Years:     ");
                yearsLabel.setVisible(false);
                yearsText.setVisible(false);
		yearsText.setColumns(10);
		rateLabel.setText("Interest Rate:    ");
                rateLabel.setVisible(false);
		rateText.setVisible(false);
                yearsText.setColumns(10);
                chooseLabel.setVisible(true);
		}
        public void drawGraph() // this will draw the graph "somehow"
        {
            
        }

        public class GraphProgram extends JPanel

	{
		GraphProgram.GraphCanvas graph = new GraphProgram.GraphCanvas();

		public GraphProgram()
		{
			setLayout(new BorderLayout());
			setSize(300, 300);

			add(graph, BorderLayout.CENTER);
		}

		public  void setValues(double[] values) {
			graph.setValues(values);
		}
		public class CoordCanvas extends Canvas
		{
			protected float viewLeft;
			protected float viewRight;
			protected float viewTop;
			protected float viewBottom;

			public void setXRange(float left, float right)
			{
				viewLeft = left;
				viewRight = right;
			}

			public void setYRange(float top, float bottom)
			{
				viewTop = top;
				viewBottom = bottom;
			}

			public float toX(float x)
			{
				return (x - viewLeft) * getSize().width / (viewRight - viewLeft);
			}

			public float toY(float y)
			{
				return (y - viewTop) * getSize().height / (viewBottom - viewTop);
			}

			public float toWidth(float w)
			{
				return w * getSize().width / Math.abs(viewRight - viewLeft);
			}

			public float toHeight(float h)
			{
				return h * getSize().height / Math.abs(viewBottom - viewTop);
			}
		}


		//  subclass to draw a bar graph

		class GraphCanvas extends GraphProgram.CoordCanvas
		{
			private double[] vals = null;

			public  void setValues(double[] vals)
			{
				this.vals = vals;
				repaint();
			}

			public  void paint(Graphics comp)
			{
				if (vals == null || vals.length < 1)
					return;

				// find maximum value
				double max = vals[0];
				for (int i = 0; i < vals.length; i++)
					if (vals[i] > max)
						max = vals[i];

				// set coordinate ranges
				this.setXRange(0F, (float)vals.length);
				this.setYRange((float)max, 0F);

				// draw the graph
				Graphics2D comp2D = (Graphics2D)comp;
				for (int i = 0; i < vals.length; i++)
				{
					Rectangle2D.Float principal = new Rectangle2D.Float(toX((float)i),
							toY((float)vals[i]), toWidth(1F), toHeight((float)vals[i]));
					comp2D.fill(principal);
				}
			}
			
		}
	
        }
        
	
}


This post has been edited by macosxnerd101: 27 January 2012 - 07:52 PM
Reason for edit:: Renamed title to be more descriptive


Is This A Good Question/Topic? 0
  • +

Replies To: Mortgage Calculator with GUI

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9487
  • View blog
  • Posts: 35,773
  • Joined: 12-June 08

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 10:33 AM

Quote

i know these are small issues but they are the difference between pass and fail.

By chance do you have line numbers for your errors?

Quote

expected ;

Perhaps you missed a semicolon near the line of the error?
Was This Post Helpful? 0
  • +
  • -

#3 no2pencil  Icon User is offline

  • Admiral Fancy Pants
  • member icon

Reputation: 5380
  • View blog
  • Posts: 27,350
  • Joined: 10-May 07

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 10:35 AM

I'm no expert in Java, but is line 245 correct?
Was This Post Helpful? 0
  • +
  • -

#4 ianian112  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 119
  • View blog
  • Posts: 378
  • Joined: 28-November 09

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 10:36 AM


Mortgage[] mortgage = new mortgage(0);
mortgage(0) = {"Select Mortgage"};                       
for (int i = 0; i less than terms.length; i++)
{
Mortgage[i] = years[i] + “years…” + terms[i] + “%”;
}



I have no clue what are you even trying to do here. But I'll try
Mortgage[i] --> mortgage[i]
mortgage(0) = {"Select Mortgage"};    --> mortgage[0] = "Select Mortgage";


as for the Mortgage[] mortgage = new mortgage(0); line and the for statement you will have to fix that by yourself because I have no clue what you are trying to do.

@noPencil: yes it is correct, but looks incorrect due to how it is indented

This post has been edited by ianian112: 27 January 2012 - 10:38 AM

Was This Post Helpful? 0
  • +
  • -

#5 jon.kiparsky  Icon User is offline

  • Pancakes!
  • member icon


Reputation: 7950
  • View blog
  • Posts: 13,540
  • Joined: 19-March 11

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 10:37 AM

There's some smelly code in there, too much to really address other than in general terms.

Generally, "illegal start of expression" means you've missed some punctuation, either a closing curly brace or a semicolon. And "; expected" probably means that you've missed out a semicolon. Try going to where the error is and fixing that.

One thing jumps out at me about the code - why is "mortgage" an array of Strings? That smells funny.

And in this line
Mortgage[] mortgage = new mortgage(0);


I don't know if you meant to call a method called mortgage with zero as a parameter, and assign the result to an array of Mortgage objects which is called mortgage, but that's what you're doing.

The whole thing makes me think of Joseph Heller's character "Major Major Major Major". Again, it's a bit smelly. But since you haven't included the stack trace of your errors, I would only be able to resolve this by searching on the word "mortgage", and I'm not going to to waste my time doing that in this stack of code.
So good luck.
Was This Post Helpful? 0
  • +
  • -

#6 thelgar  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 14
  • Joined: 27-January 12

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 10:42 AM

View Postianian112, on 27 January 2012 - 10:36 AM, said:


Mortgage[] mortgage = new mortgage(0);
mortgage(0) = {"Select Mortgage"};                       
for (int i = 0; i less than terms.length; i++)
{
Mortgage[i] = years[i] + “years…” + terms[i] + “%”;
}



I have no clue what are you even trying to do here. But I'll try
Mortgage[i] --> mortgage[i]
mortgage(0) = {"Select Mortgage"};    --> mortgage[0] = "Select Mortgage";


as for the Mortgage[] mortgage = new mortgage(0); line and the for statement you will have to fix that by yourself because I have no clue what you are trying to do.

@noPencil: yes it is correct, but looks incorrect due to how it is indented


to be honest at this point i have no idea what i am trying to do. i have gotten my self so deeply confused. the instructions for this assignment are to read the terms and years from txt file loandata.txt, populate the combo box, and run the calculations based on the data in the text file.

the lines i am referring to is supposed to populate the combo box. i already figured out how to use readFile(); later in the program to populate the arrays. now i am having trouble with the combobox reading those arrays. and finally doing the calculation on those arrays instead of hard coded data.
Was This Post Helpful? 0
  • +
  • -

#7 thelgar  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 14
  • Joined: 27-January 12

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 01:42 PM

View Postjon.kiparsky, on 27 January 2012 - 10:37 AM, said:

There's some smelly code in there, too much to really address other than in general terms.

Generally, "illegal start of expression" means you've missed some punctuation, either a closing curly brace or a semicolon. And "; expected" probably means that you've missed out a semicolon. Try going to where the error is and fixing that.

One thing jumps out at me about the code - why is "mortgage" an array of Strings? That smells funny.

And in this line
Mortgage[] mortgage = new mortgage(0);


I don't know if you meant to call a method called mortgage with zero as a parameter, and assign the result to an array of Mortgage objects which is called mortgage, but that's what you're doing.

The whole thing makes me think of Joseph Heller's character "Major Major Major Major". Again, it's a bit smelly. But since you haven't included the stack trace of your errors, I would only be able to resolve this by searching on the word "mortgage", and I'm not going to to waste my time doing that in this stack of code.
So good luck.



here is my stack trace, atleast i think this is what you are asking for.

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - illegal start of expression
at mortgagecalc.MortgageCalc.getJPanel(MortgageCalc.java:182)
at mortgagecalc.MortgageCalc.initialize(MortgageCalc.java:111)
at mortgagecalc.MortgageCalc.<init>(MortgageCalc.java:105)
at mortgagecalc.MortgageCalc$7.run(MortgageCalc.java:617)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:646)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:607)
at java.awt.EventQueue$1.run(EventQueue.java:605)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:616)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Was This Post Helpful? 0
  • +
  • -

#8 thelgar  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 14
  • Joined: 27-January 12

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 02:23 PM

well, i have corrected a bit of my issues since my last post. A good nap helped greatly. here is my new code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*Mortgage Calculator
 * Created by
 * Luther Mann
 * 1/8/2012
 * 
 * PRG 421
 * University of phoenix
 * Change request 4 (1/8/2012)
 * Change request 5 (1/15/2012)(total Code rewrite. New code is more understandable.
 * Change request 6 (1/22/2012) (add two radio buttons to allow user to manipulate code.)
 * Change request 7 (1/15/2012 ) (add data from datafile, add a graph to show the changes in principal owed.
 */



package mortgagecalc;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Canvas;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.*;
import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.border.LineBorder;



public class MortgageCalc extends JFrame {
        
        final ArrayList<Double> rateList = new ArrayList<Double>();
        final ArrayList<Integer> yearList = new ArrayList<Integer>();
	//String mortgage[] = { "Select Mortgage" };
	//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 mainTitle = null;
	JLabel principalLabel = null;
	JTextField principalText = null;
	JLabel yearsLabel = null;
	JTextField yearsText = null;
	JLabel rateLabel = null;
	JTextField rateText = null;
	JLabel chooseLabel = null;
	JComboBox chooseCombo = null;
	JRadioButton selectionOne = null;
	JRadioButton selectionTwo = null;
	ButtonGroup buttongroup = null;

	// GUI text area for results with scroll pane
	JTextArea result = null;
        JTextArea GraphArea = new JTextArea(19,50);
	JScrollPane scrollingResults = null;

	// GUI for Table with scroll pane
	MyJTable totalAmounts = null;
        JScrollPane scrollingTable = null;
        MyDTableModel model;

	// Creates button for graphing
	JButton graphButton = null;

        // Creates the button for calculation of the mortgage payments
	JButton calculateButton = null;

	// Creates a button for reset button
	JButton resetButton = null;
	
	// Declaration of variables
        int numberOfLinesGenerated=1;
        double numberYears; //term mortgage
        double principal; // amount borrowed
        double rate;  // interest for mortgage
        double monthlyPayment;  // monthly payment for mortgage
        double monthlyRate ; // monthly interest
        double totalMonths; // number of months for mortgage payments
        double interestPaid; //interest amount added for each month
        double principalPaid;

	// This is the class constructor - initialize the components

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

	// Window size, JPanel, setTitle
	public void initialize() {
		this.setSize(720, 670);
		this.setContentPane(getJPanel());
		this.setTitle("Mortgage Calculator by Luther Mann");
	}

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

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

			// Main Title of the Calculator
			mainTitle = new JLabel();
			mainTitle.setHorizontalAlignment(SwingConstants.CENTER);
			mainTitle.setBounds(130, 20, 400, 30);
			mainTitle.setText("Luther's Loan Calculator");
			mainTitle.setFont(new Font("Times New Roman", Font.BOLD, 30));
			mainTitle.setForeground(Color.blue);
			contentPanel.add(mainTitle);
                        
                        //Selection button 1
                        selectionOne = new JRadioButton();
                        selectionOne.setHorizontalAlignment(SwingConstants.CENTER);
                        selectionOne.setBounds(125, 65, 160, 15);
                        selectionOne.setText("Preset Loan Terms");
                        selectionOne.setFont(new Font("Times New Roman", Font.BOLD, 15));
                        selectionOne.setForeground(Color.black);
                        selectionOne.setSelected(true);
                        contentPanel.add(selectionOne);
                
                        //Selection Button 2
                        selectionTwo = new JRadioButton();
                        selectionTwo.setHorizontalAlignment(SwingConstants.CENTER);
                        selectionTwo.setBounds(350, 65, 180, 15);
                        selectionTwo.setText("Enter Your Loan Terms");
                        selectionTwo.setFont(new Font("Times New Roman", Font.BOLD, 15));
                        selectionTwo.setForeground(Color.black);
                        contentPanel.add(selectionTwo);

			// Principal Label
			principalLabel = new JLabel();
			principalLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			principalLabel.setBounds(120, 65, 200, 75);
			principalLabel.setText("Mortgage Principle Amount : ");
			principalLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
			principalLabel.setForeground(Color.blue);
			contentPanel.add(principalLabel);

			// Principal Text Field Features
			principalText = new JTextField();
			principalText.setBounds(350, 90, 160, 25);
			contentPanel.add(principalText);

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

			
                        
                        // String for Mortgage Variation
			String mortgage[] = new String[yearList.size() + 1];
                        //int i = 0;
                        mortgage[0] = "Select Mortgage";
                        
                        for (int i = 0; i <= rateList.size() + 1; i++)
                        {
                        mortgage[i] = yearList.get(i) + "years" + rateList.get(i) +"%";
                }
                                                
			chooseCombo = new JComboBox(mortgage);
			chooseCombo.setBounds(350, 125, 180, 30);
			chooseCombo.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					setMortgage();
				}
			});
			contentPanel.add(chooseCombo);
			
			
			// Text Area for result
			result = new JTextArea(5, 20);
                        result.setEditable(false);
			result.setBounds(170, 250, 350, 75);
			scrollingResults = new JScrollPane(result);
			contentPanel.add(result);
			
			//Table for amortization calculations
			totalAmounts = new MyJTable();
			scrollingTable = new JScrollPane (totalAmounts);
			scrollingTable.setBounds(25, 425, 600, 175);
			contentPanel.add(scrollingTable);

			// Number of Years Label
			yearsLabel = new JLabel();
			yearsLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			yearsLabel.setBounds(90, 200, 220, 25);
			yearsLabel.setText("Mortgage Term : ");
			yearsLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
			yearsLabel.setForeground(Color.blue);
                        yearsLabel.setVisible(false);
			contentPanel.add(yearsLabel);

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

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

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

			// Button for Graphing
			graphButton = new JButton();
			graphButton.setBounds(395, 350, 110, 30);
			graphButton.setText("Graph");
			contentPanel.add(graphButton);

			// Button for reset button
			resetButton = new JButton();
			resetButton.setBounds(285, 350, 110, 30);
			resetButton.setText("Reset");
			contentPanel.add(resetButton);

			// Button for calculation of the mortgage payments
			calculateButton = new JButton();
			calculateButton.setBounds(175, 350, 110, 30);
			calculateButton.setText("Calculate");
			contentPanel.add(calculateButton);

			// ---- Radio Button Listeners
                        selectionOne.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
			hideSelectionTwo();
                        }
                        });
                        selectionTwo.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
			
                        // ---- display results 
                	displaySelectionTwo();
			}
                        });

                        
                        // Action listener to the reset button

			resetButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					onButtonreset();
				}
			});
			
			
			graphButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					drawGraph();
				}
			});
			

			calculateButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					principal=getDouble(principalText.getText());
					calculate();
				{
			
			//Gets the values from the combo box or text box
                                    
	if (selectionOne.isSelected()){
            String str = (String)chooseCombo.getSelectedItem();
           if (str.equals("30 years at 5.75%")) {
	        rate = 0.0575;
	        numberYears = 30;
		          }
           else
               if(str.equals("20 years at 5.65%")) {
                   rate = 0.0565;
                   numberYears = 20;
               }
           
            else			
                if(str.equals("10 years at 5%")) {
                    rate = 0.055;
                    numberYears = 10;
                        }
            else
                if(str.equals("7 years at 5.35%")) {
                rate = 0.0535;
                numberYears = 7;
                }
           
        }
        else {
            
                rate = Double.parseDouble(rateText.getText());
                numberYears = Double.parseDouble(yearsText.getText());
                
                rate = rate/100;
           
           }
         
                 }                    
					  
			 //Calculates the number of months for mortgage
			 
                    totalMonths = numberYears * 12;

          //Caluclates the monthly interest rate
			 
                    monthlyRate = rate/12.0;

          //Calculates the monthly payment for mortgage
			 
                    monthlyPayment = (principal* monthlyRate)/(1 - Math.pow(1 + monthlyRate, -totalMonths));


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

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

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

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

        return contentPanel;
    }
        public void readFile()
        {
          String dataFileName = "/loandata.txt";

		//create arrays to hold values in file
		//final ArrayList<Double> rateList = new ArrayList<Double>();
		//final ArrayList<Integer> yearList = new ArrayList<Integer>();

		//open and read text file
		try
		{
			BufferedReader br = new BufferedReader(new FileReader(dataFileName));
			String line;

			while ((line = br.readLine()) != null)
			{
				String values[] = line.split(","); //splits each word after comma and stores values in array "values"
				int value1 = Integer.parseInt(values[0]); //sets integer value1 = first word of each line
				double value2 = Double.parseDouble(values[1]); //sets double value2 = second word of each line

				yearList.add(value1); //adds all value1 integers to arraylist
				rateList.add(value2); //adds all value2 doubles to arraylist
			}

			br.close();
		}

		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}

		catch (IOException e)
		{
			e.printStackTrace();
		}  
        }
			
//setMortgage Calculation//

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

		if (str.equals("30 years at 5.75%")) {
			rateText.setText("0.0575");
			yearsText.setText("30");
			}
                else			
                    if(str.equals("20 years at 5.65%")) {
                    rateText.setText("0.0565");
                    yearsText.setText("20");
                    }
		else			
                    if(str.equals("10 years at 5%")) {
                    rateText.setText("0.05");
                    yearsText.setText("10");
                    }
                else
                    if(str.equals("7 years at 5.35%")) {
                    rateText.setText("0.0535");
                    yearsText.setText("7");	
		}
                
            }
               
        

	
// Information for Reset Button//
	
	public void onButtonreset() {
		principalText.setText("");
		rateText.setText("");
		yearsText.setText("");
                result.setText("");
                model.setRowCount(0);
	}

// Calculate() call//
	
	public void calculate() {	
		double principal = getDouble(principalText.getText());
		int number_of_years = Integer.parseInt(yearsText.getText());
		double interest_rate = getDouble(rateText.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)); 
                
                GraphArea.append("" + principalPaid);
													// monthlyPayment
	}
	
// This the Scroll pane for the table - sets the boundaries//
    public JScrollPane getScrollPane() {
        if (scrollingTable == null) {
            scrollingTable = new JScrollPane();
            scrollingTable.setBounds(65, 225, 425, 120);
            scrollingTable.setViewportView(getTable());
        }
        return scrollingTable;
    }

    public JTable getTable() {
        if (totalAmounts == null) {
                totalAmounts = new MyJTable(getModel());
        }
        return totalAmounts;
    }
	 
	
	
//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 && rate != 0 && numberYears != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < totalMonths; i++) {
                Object data[] = new Object[6];
                data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthlyPayment);
                data[3] = nf.format(interestPaid = principal * monthlyRate);
                data[4] = nf.format(principalPaid = monthlyPayment - interestPaid);
                data[5] = nf.format(principal = principal - principalPaid);
                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() {
                MortgageCalc thisClass = new MortgageCalc();
                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);

        }

    }
        
    //used to hide and show the correct components
        public void displaySelectionTwo() {  
        
                chooseCombo.setVisible(false);
		selectionTwo.setSelected(true);
		selectionOne.setSelected(false);
		yearsLabel.setVisible(true);
                yearsLabel.setText("Loan Term Years:    ");
		yearsText.setVisible(true);
                yearsText.setEditable(true);
		rateText.setVisible(true);
                rateText.setEditable(true);
		rateLabel.setVisible(true);
                chooseLabel.setVisible(false);
                rateLabel.setText("Interest Rate     :");
		
        }
        public void hideSelectionTwo() {
		chooseCombo.setVisible(true);
		selectionTwo.setSelected(false);
		selectionOne.setSelected(true);
		principalLabel.setText("Please Select Loan:   ");
		rateLabel.setVisible(false);
		yearsLabel.setText("Years:     ");
                yearsLabel.setVisible(false);
                yearsText.setVisible(false);
		yearsText.setColumns(10);
		rateLabel.setText("Interest Rate:    ");
                rateLabel.setVisible(false);
		rateText.setVisible(false);
                yearsText.setColumns(10);
                chooseLabel.setVisible(true);
		}
        public void drawGraph() // this will draw the graph "somehow"
        {
            
        }

        public class GraphProgram extends JPanel

	{
		GraphProgram.GraphCanvas graph = new GraphProgram.GraphCanvas();

		public GraphProgram()
		{
			setLayout(new BorderLayout());
			setSize(300, 300);

			add(graph, BorderLayout.CENTER);
		}

		public  void setValues(double[] values) {
			graph.setValues(values);
		}
		public class CoordCanvas extends Canvas
		{
			protected float viewLeft;
			protected float viewRight;
			protected float viewTop;
			protected float viewBottom;

			public void setXRange(float left, float right)
			{
				viewLeft = left;
				viewRight = right;
			}

			public void setYRange(float top, float bottom)
			{
				viewTop = top;
				viewBottom = bottom;
			}

			public float toX(float x)
			{
				return (x - viewLeft) * getSize().width / (viewRight - viewLeft);
			}

			public float toY(float y)
			{
				return (y - viewTop) * getSize().height / (viewBottom - viewTop);
			}

			public float toWidth(float w)
			{
				return w * getSize().width / Math.abs(viewRight - viewLeft);
			}

			public float toHeight(float h)
			{
				return h * getSize().height / Math.abs(viewBottom - viewTop);
			}
		}


		//  subclass to draw a bar graph

		class GraphCanvas extends GraphProgram.CoordCanvas
		{
			private double[] vals = null;

			public  void setValues(double[] vals)
			{
				this.vals = vals;
				repaint();
			}

			public  void paint(Graphics comp)
			{
				if (vals == null || vals.length < 1)
					return;

				// find maximum value
				double max = vals[0];
				for (int i = 0; i < vals.length; i++)
					if (vals[i] > max)
						max = vals[i];

				// set coordinate ranges
				this.setXRange(0F, (float)vals.length);
				this.setYRange((float)max, 0F);

				// draw the graph
				Graphics2D comp2D = (Graphics2D)comp;
				for (int i = 0; i < vals.length; i++)
				{
					Rectangle2D.Float principal = new Rectangle2D.Float(toX((float)i),
							toY((float)vals[i]), toWidth(1F), toHeight((float)vals[i]));
					comp2D.fill(principal);
				}
			}
			
		}
	
        }
        
	
}




i am getting these errors in the stack trace:

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at mortgagecalc.MortgageCalc.getJPanel(MortgageCalc.java:185)
at mortgagecalc.MortgageCalc.initialize(MortgageCalc.java:111)
at mortgagecalc.MortgageCalc.<init>(MortgageCalc.java:105)
at mortgagecalc.MortgageCalc$7.run(MortgageCalc.java:618)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:646)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:607)
at java.awt.EventQueue$1.run(EventQueue.java:605)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:616)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)


any advice. i know i am somehow screwing up the array and overflowing but i cannot see where.
Was This Post Helpful? 0
  • +
  • -

#9 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2205
  • View blog
  • Posts: 5,239
  • Joined: 10-September 10

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 02:30 PM

This line,

(183) for (int i = 0; i <= rateList.size() + 1; i++)

looks suspicious. If the variable 'i' is used as an index, you should use < .size().
Was This Post Helpful? 2
  • +
  • -

#10 thelgar  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 14
  • Joined: 27-January 12

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 02:55 PM

View PostGregBrannon, on 27 January 2012 - 02:30 PM, said:

This line,

(183) for (int i = 0; i <= rateList.size() + 1; i++)

looks suspicious. If the variable 'i' is used as an index, you should use < .size().



thanks greg. i got this one. it turns out i needed to use
                for (int i = 0; i < rateList.size(); i++)
                        {
                        mortgage[i + 1] = yearList.get(i) + " years " + rateList.get(i) +"%";
                }


Was This Post Helpful? 0
  • +
  • -

#11 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10771
  • View blog
  • Posts: 40,102
  • Joined: 27-December 08

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 07:52 PM

Duplicate threads merged. Please avoid duplicate posting.
Was This Post Helpful? 0
  • +
  • -

#12 thelgar  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 14
  • Joined: 27-January 12

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 09:15 PM

ok just about done with the calculations and the combo box. one last issue. everything works unless the user re-selects the "Select Mortgage" line then it crashes because the index becomes - 1

package mortgagecalc;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Canvas;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.*;
import java.text.DecimalFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.border.LineBorder;



public class MortgageCalc extends JFrame {
        
        final ArrayList<Double> rateList = new ArrayList<Double>();
        final ArrayList<Integer> yearList = new ArrayList<Integer>();
	//String mortgage[] = { "Select Mortgage" };
	//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 mainTitle = null;
	JLabel principalLabel = null;
	JTextField principalText = null;
	JLabel yearsLabel = null;
	JTextField yearsText = null;
	JLabel rateLabel = null;
	JTextField rateText = null;
	JLabel chooseLabel = null;
	JComboBox chooseCombo = null;
	JRadioButton selectionOne = null;
	JRadioButton selectionTwo = null;
	ButtonGroup buttongroup = null;

	// GUI text area for results with scroll pane
	JTextArea result = null;
        JTextArea GraphArea = new JTextArea(19,50);
	JScrollPane scrollingResults = null;

	// GUI for Table with scroll pane
	MyJTable totalAmounts = null;
        JScrollPane scrollingTable = null;
        MyDTableModel model;

	// Creates button for graphing
	JButton graphButton = null;

        // Creates the button for calculation of the mortgage payments
	JButton calculateButton = null;

	// Creates a button for reset button
	JButton resetButton = null;
	
	// Declaration of variables
        int numberOfLinesGenerated=1;
        double numberYears; //term mortgage
        double principal; // amount borrowed
        double rate;  // interest for mortgage
        double monthlyPayment;  // monthly payment for mortgage
        double monthlyRate ; // monthly interest
        double totalMonths; // number of months for mortgage payments
        double interestPaid; //interest amount added for each month
        double principalPaid;

	// This is the class constructor - initialize the components

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

	// Window size, JPanel, setTitle
	public void initialize() {
		this.setSize(720, 670);
		this.setContentPane(getJPanel());
		this.setTitle("Mortgage Calculator by Luther Mann");
	}

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

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

			// Main Title of the Calculator
			mainTitle = new JLabel();
			mainTitle.setHorizontalAlignment(SwingConstants.CENTER);
			mainTitle.setBounds(130, 20, 400, 30);
			mainTitle.setText("Luther's Loan Calculator");
			mainTitle.setFont(new Font("Times New Roman", Font.BOLD, 30));
			mainTitle.setForeground(Color.blue);
			contentPanel.add(mainTitle);
                        
                        //Selection button 1
                        selectionOne = new JRadioButton();
                        selectionOne.setHorizontalAlignment(SwingConstants.CENTER);
                        selectionOne.setBounds(125, 65, 160, 15);
                        selectionOne.setText("Preset Loan Terms");
                        selectionOne.setFont(new Font("Times New Roman", Font.BOLD, 15));
                        selectionOne.setForeground(Color.black);
                        selectionOne.setSelected(true);
                        contentPanel.add(selectionOne);
                
                        //Selection Button 2
                        selectionTwo = new JRadioButton();
                        selectionTwo.setHorizontalAlignment(SwingConstants.CENTER);
                        selectionTwo.setBounds(350, 65, 180, 15);
                        selectionTwo.setText("Enter Your Loan Terms");
                        selectionTwo.setFont(new Font("Times New Roman", Font.BOLD, 15));
                        selectionTwo.setForeground(Color.black);
                        contentPanel.add(selectionTwo);

			// Principal Label
			principalLabel = new JLabel();
			principalLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			principalLabel.setBounds(120, 65, 200, 75);
			principalLabel.setText("Mortgage Principle Amount : ");
			principalLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
			principalLabel.setForeground(Color.blue);
			contentPanel.add(principalLabel);

			// Principal Text Field Features
			principalText = new JTextField();
			principalText.setBounds(350, 90, 160, 25);
			contentPanel.add(principalText);

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

			
                        
                        // String for Mortgage Variation
			String mortgage[] = new String[yearList.size() + 1];
                        
                        mortgage[0] = "Select Mortgage";
                        
                        for (int i = 0; i < rateList.size(); i++)
                        {
                        mortgage[i + 1] = yearList.get(i) + " years " + rateList.get(i) +"%";
                }
                                                
			chooseCombo = new JComboBox(mortgage);
			chooseCombo.setBounds(350, 125, 180, 30);
			chooseCombo.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					setMortgage();
				}
			});
			contentPanel.add(chooseCombo);
			
			
			// Text Area for result
			result = new JTextArea(5, 20);
                        result.setEditable(false);
			result.setBounds(170, 250, 350, 75);
			scrollingResults = new JScrollPane(result);
			contentPanel.add(result);
			
			//Table for amortization calculations
			totalAmounts = new MyJTable();
			scrollingTable = new JScrollPane (totalAmounts);
			scrollingTable.setBounds(25, 425, 600, 175);
			contentPanel.add(scrollingTable);

			// Number of Years Label
			yearsLabel = new JLabel();
			yearsLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			yearsLabel.setBounds(90, 200, 220, 25);
			yearsLabel.setText("Mortgage Term : ");
			yearsLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
			yearsLabel.setForeground(Color.blue);
                        //yearsLabel.setVisible(false);
			contentPanel.add(yearsLabel);

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

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

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

			// Button for Graphing
			graphButton = new JButton();
			graphButton.setBounds(395, 350, 110, 30);
			graphButton.setText("Graph");
			contentPanel.add(graphButton);

			// Button for reset button
			resetButton = new JButton();
			resetButton.setBounds(285, 350, 110, 30);
			resetButton.setText("Reset");
			contentPanel.add(resetButton);

			// Button for calculation of the mortgage payments
			calculateButton = new JButton();
			calculateButton.setBounds(175, 350, 110, 30);
			calculateButton.setText("Calculate");
			contentPanel.add(calculateButton);

			// ---- Radio Button Listeners
                        selectionOne.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
			hideSelectionTwo();
                        }
                        });
                        selectionTwo.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
			
                        // ---- display results 
                	displaySelectionTwo();
			}
                        });

                        
                        // Action listener to the reset button

			resetButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					onButtonreset();
				}
			});
			
			
			graphButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					drawGraph();
				}
			});
			

			calculateButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					principal=getDouble(principalText.getText());
					calculate();
				{
			
			//Gets the values from the combo box or text box
                                    
	if (selectionOne.isSelected()){
             int index = (int)chooseCombo.getSelectedIndex();
                rateList.get(index);
                yearList.get(index);
                rate = rateList.get(index);
                numberYears = yearList.get(index);
                 
            /*if (str.equals("30 years at 5.75%")) {
	        rate = 0.0575;
	        numberYears = 30;
		          }
           else
               if(str.equals("20 years at 5.65%")) {
                   rate = 0.0565;
                   numberYears = 20;
               }
           
            else			
                if(str.equals("10 years at 5%")) {
                    rate = 0.055;
                    numberYears = 10;
                        }
            else
                if(str.equals("7 years at 5.35%")) {
                rate = 0.0535;
                numberYears = 7;
                }
           
        }*/
        //else {
            
                rate = Double.parseDouble(rateText.getText());
                numberYears = Double.parseDouble(yearsText.getText());
                
                rate = rate/100;
           
           }
         
                 }                    
					  
			 //Calculates the number of months for mortgage
			 
                    totalMonths = numberYears * 12;

          //Caluclates the monthly interest rate
			 
                    monthlyRate = rate/12.0;

          //Calculates the monthly payment for mortgage
			 
                    monthlyPayment = (principal* monthlyRate)/(1 - Math.pow(1 + monthlyRate, -totalMonths));


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

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

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

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

        return contentPanel;
    }
        public void readFile()
        {
          String dataFileName = "loandata.txt";

		//create arrays to hold values in file
		//final ArrayList<Double> rateList = new ArrayList<Double>();
		//final ArrayList<Integer> yearList = new ArrayList<Integer>();

		//open and read text file
		try
		{
			BufferedReader br = new BufferedReader(new FileReader(dataFileName));
			String line;

			while ((line = br.readLine()) != null)
			{
				String values[] = line.split(","); //splits each word after comma and stores values in array "values"
				int value1 = Integer.parseInt(values[0]); //sets integer value1 = first word of each line
				double value2 = Double.parseDouble(values[1]); //sets double value2 = second word of each line

				yearList.add(value1); //adds all value1 integers to arraylist
				rateList.add(value2); //adds all value2 doubles to arraylist
			}

			br.close();
		}

		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}

		catch (IOException e)
		{
			e.printStackTrace();
		}  
        }
			
//setMortgage Calculation//

	public void setMortgage() {
            
            int index = (int)chooseCombo.getSelectedIndex();
            if (index <= 0 );
            {
                
            }
                //rateList.get(index);
                //yearList.get(index);
                double rateTemp = rateList.get(index - 1);
                int yearsTemp = yearList.get(index - 1);
                String rateString = Double.toString(rateTemp);
                String yearString = Integer.toString(yearsTemp);
                
                rateText.setText(rateString);
                yearsText.setText(yearString);
            
            
		/*String str = (String) chooseCombo.getSelectedItem();

		if (str.equals("30 years at 5.75%")) {
			rateText.setText("0.0575");
			yearsText.setText("30");
			}
                else			
                    if(str.equals("20 years at 5.65%")) {
                    rateText.setText("0.0565");
                    yearsText.setText("20");
                    }
		else			
                    if(str.equals("10 years at 5%")) {
                    rateText.setText("0.05");
                    yearsText.setText("10");
                    }
                else
                    if(str.equals("7 years at 5.35%")) {
                    rateText.setText("0.0535");
                    yearsText.setText("7");	
		}*/
                
            }
               
        

	
// Information for Reset Button//
	
	public void onButtonreset() {
		principalText.setText("");
		rateText.setText("");
		yearsText.setText("");
                result.setText("");
                model.setRowCount(0);
	}

// Calculate() call//
	
	public void calculate() {	
		double principal = getDouble(principalText.getText());
		int number_of_years = Integer.parseInt(yearsText.getText());
		double interest_rate = getDouble(rateText.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)); 
                
                GraphArea.append("" + principalPaid);
													// monthlyPayment
	}
	
// This the Scroll pane for the table - sets the boundaries//
    public JScrollPane getScrollPane() {
        if (scrollingTable == null) {
            scrollingTable = new JScrollPane();
            scrollingTable.setBounds(65, 225, 425, 120);
            scrollingTable.setViewportView(getTable());
        }
        return scrollingTable;
    }

    public JTable getTable() {
        if (totalAmounts == null) {
                totalAmounts = new MyJTable(getModel());
        }
        return totalAmounts;
    }
	 
	
	
//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 && rate != 0 && numberYears != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < totalMonths; i++) {
                Object data[] = new Object[6];
                data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthlyPayment);
                data[3] = nf.format(interestPaid = principal * monthlyRate);
                data[4] = nf.format(principalPaid = monthlyPayment - interestPaid);
                data[5] = nf.format(principal = principal - principalPaid);
                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() {
                MortgageCalc thisClass = new MortgageCalc();
                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);

        }

    }
        
    //used to hide and show the correct components
        public void displaySelectionTwo() {  
        
                chooseCombo.setVisible(false);
		selectionTwo.setSelected(true);
		selectionOne.setSelected(false);
		yearsLabel.setVisible(true);
                yearsLabel.setText("Loan Term Years:    ");
		yearsText.setVisible(true);
                yearsText.setEditable(true);
		rateText.setVisible(true);
                rateText.setEditable(true);
		rateLabel.setVisible(true);
                chooseLabel.setVisible(false);
                rateLabel.setText("Interest Rate     :");
		
        }
        public void hideSelectionTwo() {
		chooseCombo.setVisible(true);
		selectionTwo.setSelected(false);
		selectionOne.setSelected(true);
		principalLabel.setText("Please Select Loan:   ");
		rateLabel.setVisible(false);
		yearsLabel.setText("Years:     ");
                yearsLabel.setVisible(false);
                yearsText.setVisible(false);
		yearsText.setColumns(10);
		rateLabel.setText("Interest Rate:    ");
                rateLabel.setVisible(false);
		rateText.setVisible(false);
                yearsText.setColumns(10);
                chooseLabel.setVisible(true);
		}
        public void drawGraph() // this will draw the graph "somehow"
        {
            
        }

        public class GraphProgram extends JPanel

	{
		GraphProgram.GraphCanvas graph = new GraphProgram.GraphCanvas();

		public GraphProgram()
		{
			setLayout(new BorderLayout());
			setSize(300, 300);

			add(graph, BorderLayout.CENTER);
		}

		public  void setValues(double[] values) {
			graph.setValues(values);
		}
		public class CoordCanvas extends Canvas
		{
			protected float viewLeft;
			protected float viewRight;
			protected float viewTop;
			protected float viewBottom;

			public void setXRange(float left, float right)
			{
				viewLeft = left;
				viewRight = right;
			}

			public void setYRange(float top, float bottom)
			{
				viewTop = top;
				viewBottom = bottom;
			}

			public float toX(float x)
			{
				return (x - viewLeft) * getSize().width / (viewRight - viewLeft);
			}

			public float toY(float y)
			{
				return (y - viewTop) * getSize().height / (viewBottom - viewTop);
			}

			public float toWidth(float w)
			{
				return w * getSize().width / Math.abs(viewRight - viewLeft);
			}

			public float toHeight(float h)
			{
				return h * getSize().height / Math.abs(viewBottom - viewTop);
			}
		}


		//  subclass to draw a bar graph

		class GraphCanvas extends GraphProgram.CoordCanvas
		{
			private double[] vals = null;

			public  void setValues(double[] vals)
			{
				this.vals = vals;
				repaint();
			}

			public  void paint(Graphics comp)
			{
				if (vals == null || vals.length < 1)
					return;

				// find maximum value
				double max = vals[0];
				for (int i = 0; i < vals.length; i++)
					if (vals[i] > max)
						max = vals[i];

				// set coordinate ranges
				this.setXRange(0F, (float)vals.length);
				this.setYRange((float)max, 0F);

				// draw the graph
				Graphics2D comp2D = (Graphics2D)comp;
				for (int i = 0; i < vals.length; i++)
				{
					Rectangle2D.Float principal = new Rectangle2D.Float(toX((float)i),
							toY((float)vals[i]), toWidth(1F), toHeight((float)vals[i]));
					comp2D.fill(principal);
				}
			}
			
		}
	
        }
        
	
}




next stop the graph!!!! :(
Was This Post Helpful? 0
  • +
  • -

#13 thelgar  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 14
  • Joined: 27-January 12

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 09:37 PM

ok i changed this section:

int index = (int)chooseCombo.getSelectedIndex();
                try {
                if (index <= 0 );
                {
                
                }
                //rateList.get(index);
                //yearList.get(index);
                    double rateTemp = rateList.get(index - 1);
                    int yearsTemp = yearList.get(index - 1);
                    String rateString = Double.toString(rateTemp);
                    String yearString = Integer.toString(yearsTemp);
                
                    rateText.setText(rateString);
                    yearsText.setText(yearString);
            
            
		/*String str = (String) chooseCombo.getSelectedItem();

		if (str.equals("30 years at 5.75%")) {
			rateText.setText("0.0575");
			yearsText.setText("30");
			}
                else			
                    if(str.equals("20 years at 5.65%")) {
                    rateText.setText("0.0565");
                    yearsText.setText("20");
                    }
		else			
                    if(str.equals("10 years at 5%")) {
                    rateText.setText("0.05");
                    yearsText.setText("10");
                    }
                else
                    if(str.equals("7 years at 5.35%")) {
                    rateText.setText("0.0535");
                    yearsText.setText("7");	
		}*/
            }catch (java.lang.ArrayIndexOutOfBoundsException e){
                
            }



i would like the exception handler to clear both the rateText and yearsText fields. any tips on how to handle that?
Was This Post Helpful? 0
  • +
  • -

#14 thelgar  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 14
  • Joined: 27-January 12

Re: Mortgage Calculator with GUI

Posted 27 January 2012 - 10:02 PM

finally got it. Thanks everyone. no more errors. Tomorrow i need to start on the Graph. Good nite everyone!
Was This Post Helpful? 0
  • +
  • -

#15 thelgar  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 14
  • Joined: 27-January 12

Re: Mortgage Calculator with GUI

Posted 28 January 2012 - 08:21 AM

ok good morning everyone. today i need to get this graph working. its supposed to be a simple line graph that shows the progress of the remaining loan balance (principal) over the duration of the loan. I would like it to be a new window, but am completely lost for HOW to make it a window, and also how to even finish the code from where i am. so...

1) what am i forgetting to do to get the graph, since nothing currently displays.
2) how do i go about making it a pop-up window?
3) how do i get the graph to read the remaining balance from the calculations at each step?


package mortgagecalc;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;



public class MortgageCalc extends JFrame {
        
        final ArrayList<Double> rateList = new ArrayList<Double>();
        final ArrayList<Integer> yearList = new ArrayList<Integer>();
	//String mortgage[] = { "Select Mortgage" };
	//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 mainTitle = null;
	JLabel principalLabel = null;
	JTextField principalText = null;
	JLabel yearsLabel = null;
	JTextField yearsText = null;
	JLabel rateLabel = null;
	JTextField rateText = null;
	JLabel chooseLabel = null;
	JComboBox chooseCombo = null;
	JRadioButton selectionOne = null;
	JRadioButton selectionTwo = null;
	ButtonGroup buttongroup = null;

	// GUI text area for results with scroll pane
	JTextArea result = null;
        JTextArea GraphArea = new JTextArea(19,50);
	JScrollPane scrollingResults = null;

	// GUI for Table with scroll pane
	MyJTable totalAmounts = null;
        JScrollPane scrollingTable = null;
        MyDTableModel model;

	// Creates button for graphing
	JButton graphButton = null;

        // Creates the button for calculation of the mortgage payments
	JButton calculateButton = null;

	// Creates a button for reset button
	JButton resetButton = null;
	
	// Declaration of variables
        int numberOfLinesGenerated=1;
        double numberYears; //term mortgage
        double principal; // amount borrowed
        double rate;  // interest for mortgage
        double monthlyPayment;  // monthly payment for mortgage
        double monthlyRate ; // monthly interest
        double totalMonths; // number of months for mortgage payments
        double interestPaid; //interest amount added for each month
        double principalPaid;

	// This is the class constructor - initialize the components

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

	// Window size, JPanel, setTitle
	public void initialize() {
		this.setSize(720, 670);
		this.setContentPane(getJPanel());
		this.setTitle("Mortgage Calculator by Luther Mann");
	}

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

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

			// Main Title of the Calculator
			mainTitle = new JLabel();
			mainTitle.setHorizontalAlignment(SwingConstants.CENTER);
			mainTitle.setBounds(130, 20, 400, 30);
			mainTitle.setText("Luther's Loan Calculator");
			mainTitle.setFont(new Font("Times New Roman", Font.BOLD, 30));
			mainTitle.setForeground(Color.blue);
			contentPanel.add(mainTitle);
                        
                        //Selection button 1
                        selectionOne = new JRadioButton();
                        selectionOne.setHorizontalAlignment(SwingConstants.CENTER);
                        selectionOne.setBounds(125, 65, 160, 15);
                        selectionOne.setText("Preset Loan Terms");
                        selectionOne.setFont(new Font("Times New Roman", Font.BOLD, 15));
                        selectionOne.setForeground(Color.black);
                        selectionOne.setSelected(true);
                        contentPanel.add(selectionOne);
                
                        //Selection Button 2
                        selectionTwo = new JRadioButton();
                        selectionTwo.setHorizontalAlignment(SwingConstants.CENTER);
                        selectionTwo.setBounds(350, 65, 180, 15);
                        selectionTwo.setText("Enter Your Loan Terms");
                        selectionTwo.setFont(new Font("Times New Roman", Font.BOLD, 15));
                        selectionTwo.setForeground(Color.black);
                        contentPanel.add(selectionTwo);

			// Principal Label
			principalLabel = new JLabel();
			principalLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			principalLabel.setBounds(120, 65, 200, 75);
			principalLabel.setText("Mortgage Principle Amount : ");
			principalLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
			principalLabel.setForeground(Color.blue);
			contentPanel.add(principalLabel);

			// Principal Text Field Features
			principalText = new JTextField();
			principalText.setBounds(350, 90, 160, 25);
			contentPanel.add(principalText);

			// Mortgage Plan Label
			chooseLabel = new JLabel();
			chooseLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			chooseLabel.setBounds(90, 125, 220, 25);
			chooseLabel.setText("Select Mortgage Plan : ");
			chooseLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
			chooseLabel.setForeground(Color.blue);
			contentPanel.add(chooseLabel);
                        
                        JPanel detailPanel = new JPanel();
                        
                        //create panel for graph
                        GraphCanvas view = new GraphCanvas();
                        detailPanel.add (view);

			
                        
                        // String for Mortgage Variation
			String mortgage[] = new String[yearList.size() + 1];
                        
                        mortgage[0] = "Select Mortgage";
                        
                        for (int i = 0; i < rateList.size(); i++)
                        {
                        mortgage[i + 1] = yearList.get(i) + " years " + rateList.get(i) +"%";
                }
                                                
			chooseCombo = new JComboBox(mortgage);
			chooseCombo.setBounds(350, 125, 180, 30);
			chooseCombo.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent event) {
					setMortgage();
				}
			});
			contentPanel.add(chooseCombo);
			
			
			// Text Area for result
			result = new JTextArea(5, 20);
                        result.setEditable(false);
			result.setBounds(170, 250, 350, 75);
			scrollingResults = new JScrollPane(result);
			contentPanel.add(result);
			
			//Table for amortization calculations
			totalAmounts = new MyJTable();
			scrollingTable = new JScrollPane (totalAmounts);
			scrollingTable.setBounds(25, 425, 600, 175);
			contentPanel.add(scrollingTable);

			// Number of Years Label
			yearsLabel = new JLabel();
			yearsLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			yearsLabel.setBounds(90, 200, 220, 25);
			yearsLabel.setText("Mortgage Term : ");
			yearsLabel.setFont(new Font("Times New Roman", Font.BOLD, 15));
			yearsLabel.setForeground(Color.blue);
                        //yearsLabel.setVisible(false);
			contentPanel.add(yearsLabel);

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

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

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

			// Button for Graphing
			graphButton = new JButton();
			graphButton.setBounds(395, 350, 110, 30);
			graphButton.setText("Graph");
			contentPanel.add(graphButton);

			// Button for reset button
			resetButton = new JButton();
			resetButton.setBounds(285, 350, 110, 30);
			resetButton.setText("Reset");
			contentPanel.add(resetButton);

			// Button for calculation of the mortgage payments
			calculateButton = new JButton();
			calculateButton.setBounds(175, 350, 110, 30);
			calculateButton.setText("Calculate");
			contentPanel.add(calculateButton);

			// ---- Radio Button Listeners
                        selectionOne.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
			hideSelectionTwo();
                        }
                        });
                        selectionTwo.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
			
                        // ---- display results 
                	displaySelectionTwo();
			}
                        });

                        
                        // Action listener to the reset button

			resetButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					onButtonreset();
				}
			});
			
			
			graphButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					drawGraph();
				}
			});
			

			calculateButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					principal=getDouble(principalText.getText());
					calculate();
				{
			
			//Gets the values from the combo box or text box
                                    
	if (selectionOne.isSelected()){
             int index = (int)chooseCombo.getSelectedIndex();
                rateList.get(index - 1);
                yearList.get(index - 1);
                rate = rateList.get(index - 1);
                numberYears = yearList.get(index - 1);
                 
            /*if (str.equals("30 years at 5.75%")) {
	        rate = 0.0575;
	        numberYears = 30;
		          }
           else
               if(str.equals("20 years at 5.65%")) {
                   rate = 0.0565;
                   numberYears = 20;
               }
           
            else			
                if(str.equals("10 years at 5%")) {
                    rate = 0.055;
                    numberYears = 10;
                        }
            else
                if(str.equals("7 years at 5.35%")) {
                rate = 0.0535;
                numberYears = 7;
                }
           
        }*/
        //else {
            
                rate = Double.parseDouble(rateText.getText());
                numberYears = Double.parseDouble(yearsText.getText());
                
                rate = rate/100;
           
           }
         
                 }                    
					  
			 //Calculates the number of months for mortgage
			 
                    totalMonths = numberYears * 12;

          //Caluclates the monthly interest rate
			 
                    monthlyRate = rate/12.0;

          //Calculates the monthly payment for mortgage
			 
                    monthlyPayment = (principal* monthlyRate)/(1 - Math.pow(1 + monthlyRate, -totalMonths));


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

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

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

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

        return contentPanel;
    }
        public void readFile()
        {
          String dataFileName = "/loandata.txt";

		//create arrays to hold values in file
		//final ArrayList<Double> rateList = new ArrayList<Double>();
		//final ArrayList<Integer> yearList = new ArrayList<Integer>();

		//open and read text file
		try
		{
			BufferedReader br = new BufferedReader(new FileReader(dataFileName));
			String line;

			while ((line = br.readLine()) != null)
			{
				String values[] = line.split(","); //splits each word after comma and stores values in array "values"
				int value1 = Integer.parseInt(values[0]); //sets integer value1 = first word of each line
				double value2 = Double.parseDouble(values[1]); //sets double value2 = second word of each line

				yearList.add(value1); //adds all value1 integers to arraylist
				rateList.add(value2); //adds all value2 doubles to arraylist
			}

			br.close();
		}

		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}

		catch (IOException e)
		{
			e.printStackTrace();
		}  
        }
			
//setMortgage Calculation//

	public void setMortgage() {
            
            int index = (int)chooseCombo.getSelectedIndex();
                try {
                if (index <= 0 );
                {
                
                }
                //rateList.get(index);
                //yearList.get(index);
                    double rateTemp = rateList.get(index - 1);
                    int yearsTemp = yearList.get(index - 1);
                    String rateString = Double.toString(rateTemp);
                    String yearString = Integer.toString(yearsTemp);
                
                    rateText.setText(rateString);
                    yearsText.setText(yearString);
            
            
		/*String str = (String) chooseCombo.getSelectedItem();

		if (str.equals("30 years at 5.75%")) {
			rateText.setText("0.0575");
			yearsText.setText("30");
			}
                else			
                    if(str.equals("20 years at 5.65%")) {
                    rateText.setText("0.0565");
                    yearsText.setText("20");
                    }
		else			
                    if(str.equals("10 years at 5%")) {
                    rateText.setText("0.05");
                    yearsText.setText("10");
                    }
                else
                    if(str.equals("7 years at 5.35%")) {
                    rateText.setText("0.0535");
                    yearsText.setText("7");	
		}*/
            }catch (java.lang.ArrayIndexOutOfBoundsException e){
                
            }
                
            }
               
        

	
// Information for Reset Button//
	
	public void onButtonreset() {
		principalText.setText("");
		rateText.setText("");
		yearsText.setText("");
                result.setText("");
                model.setRowCount(0);
	}

// Calculate() call//
	
	public void calculate() {	
		double principal = getDouble(principalText.getText());
		int number_of_years = Integer.parseInt(yearsText.getText());
		double interest_rate = getDouble(rateText.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)); 
                
                GraphArea.append("" + principalPaid);
													// monthlyPayment
	}
	
// This the Scroll pane for the table - sets the boundaries//
    public JScrollPane getScrollPane() {
        if (scrollingTable == null) {
            scrollingTable = new JScrollPane();
            scrollingTable.setBounds(65, 225, 425, 120);
            scrollingTable.setViewportView(getTable());
        }
        return scrollingTable;
    }

    public JTable getTable() {
        if (totalAmounts == null) {
                totalAmounts = new MyJTable(getModel());
        }
        return totalAmounts;
    }
	 
	
	
//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 && rate != 0 && numberYears != 0) {
            double new_principal = principal;
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            for (int i = 0; i < totalMonths; i++) {
                Object data[] = new Object[6];
                data[0] = Integer.toString(i + 1);
                data[1] = nf.format(new_principal);
                data[2] = nf.format(monthlyPayment);
                data[3] = nf.format(interestPaid = principal * monthlyRate);
                data[4] = nf.format(principalPaid = monthlyPayment - interestPaid);
                data[5] = nf.format(principal = principal - principalPaid);
                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() {
                MortgageCalc thisClass = new MortgageCalc();
                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);

        }

    }
        
    //used to hide and show the correct components
        public void displaySelectionTwo() {  
        
                chooseCombo.setVisible(false);
		selectionTwo.setSelected(true);
		selectionOne.setSelected(false);
		yearsLabel.setVisible(true);
                yearsLabel.setText("Loan Term Years:    ");
		yearsText.setVisible(true);
                yearsText.setEditable(true);
		rateText.setVisible(true);
                rateText.setEditable(true);
		rateLabel.setVisible(true);
                chooseLabel.setVisible(false);
                rateLabel.setText("Interest Rate     :");
		
        }
        public void hideSelectionTwo() {
		chooseCombo.setVisible(true);
		selectionTwo.setSelected(false);
		selectionOne.setSelected(true);
		principalLabel.setText("Please Select Loan:   ");
		rateLabel.setVisible(false);
		yearsLabel.setText("Years:     ");
                yearsLabel.setVisible(false);
                yearsText.setVisible(false);
		yearsText.setColumns(10);
		rateLabel.setText("Interest Rate:    ");
                rateLabel.setVisible(false);
		rateText.setVisible(false);
                yearsText.setColumns(10);
                chooseLabel.setVisible(true);
		}
        public void drawGraph() // this will draw the graph "somehow"
        {
            
        }

        class GraphCanvas extends Canvas
{

	public GraphCanvas()
	{
		setSize(450, 150);
	}

	protected int viewLeft;
	protected int viewRight;
	protected int viewTop;
	protected int viewBottom;

	public void setXRange(int left, int right)
	{
		viewLeft = left;
	    viewRight = right;
	}

	public void setYRange(int top, int bottom)
	{
	    viewTop = top;
	    viewBottom = bottom;
	}

	public int toX(int x)
	{
	    return (x - viewLeft) * getSize().width / (viewRight - viewLeft);
	}

	public int toY(int y)
	{
	    return (y - viewTop) *
	    getSize().height / (viewBottom - viewTop);
	}

	public int toWidth(int w)
	{
	    return (w * getSize().width /
	    Math.abs(viewRight - viewLeft));
	}

	public int toHeight(int h)
	{
	    return (h * getSize().height /
	    Math.abs(viewBottom - viewTop));
	}

	public void paint(Graphics g) // display shapes on canvas
	{
		// draw entire component with blue border and label
		g.setColor(Color.red);
		g.drawRect(0, 0, 449, 134);
		g.drawString("Principle Graph", 180, 20);

		int [] amount;
		amount = new int [360];

		setXRange(0, 360);
		setYRange(200000, 0);

		for (int n=0; n<360; n++)
		{
    	g.drawLine(toX(n),toY(amount[n]),toWidth(1),toHeight(amount[n]));

		}

	}

}
        
	
}



Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2