3 Replies - 1349 Views - Last Post: 07 September 2010 - 10:37 PM Rate Topic: -----

#1 Palo726  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 18-August 10

Mortgage Payment Calculator

Posted 07 September 2010 - 07:22 PM

I have a program that runs but I have a few issues...
1 - When I click on "choose rate" and then calculate it throws my exceptions.
2 - I am not sure if it is reading my loandata.txt file. I think it is because the text file is in my source packages. I have attached this file.
3 - My graph does not display.

Ok here is the code for the program and the graph if someone could lead me in the right direction with some input I would appreciate it.

package mortgagecalculatorprogram7;

/*Write the program in Java (with a graphical user interface) and have it
calculate and display the mortgage payment amount from user input of the
amount of the mortgage and the user's selection from a menu of available
mortgage loans:

- 7 years at 5.35%
- 15 years at 5.5%
- 30 years at 5.75%

Use an array for the mortgage data for the different loans. Read the
interest rates to fill the array from a sequential file. Display the
mortgage payment amount followed by the loan balance and interest paid
for each payment over the term of the loan. Add graphics in the form of a chart.
Allow the user to loop back and enter a new amount and make a new selection or quit.
Please insert comments in the program to document the program.

 */
import java.awt.*;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.io.*;

import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class mortgagecalculatorprogram7 extends JFrame implements ActionListener {

    JLabel Llabel; //amount label
    JTextField Ltextfield;//amount textfield
    JLabel Olabel;//option label
    JComboBox options;//option combobox
    JLabel Tlabel;//term label
    JTextField Ttextfield;//term textfield
    JLabel Rlabel;//rate label
    JTextField Rtextfield;//rate textfield
    JLabel Plabel;  //payment label
    JLabel $label;  //field for monthly payment amount
    JButton calculate;  //calculate button
    JButton reset;  //reset button
    JButton end;  //end button
    JTable table;//create table
    JMenuItem mnuExit = new JMenuItem("Exit");
    DefaultTableModel model;//table model
    int[] trmArray;
    double[] intrstArray;
    JButton graph;
    private float[] yearlyPrinciple;
    private float[] yearlyInterest;

    // header
    public mortgagecalculatorprogram7() {
        super("Mortgage Payment Calculator");
        setDefaultLookAndFeelDecorated(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        load();
        init();
        pack();
        setVisible(true);
    }

    //-------- READING FROM SEQUENTIAL FILE--------------
     public final void load()
     {
          Reader fis;
           try
          {
               fis = new InputStreamReader(getClass().getResourceAsStream("loandata.txt"));

                BufferedReader b = new BufferedReader( fis );


                     String[] line = b.readLine(  ).split(",");
                     trmArray = new int[line.length];
                        for ( int i = 0; i < 3; i++ )
                        {
                            trmArray[ i ] = Integer.parseInt(line[i].trim());
                        }
                    line = b.readLine(  ).split(",");
                    intrstArray = new double[line.length];
                        for ( int i = 0; i < 3; i++ )
                        {
                           intrstArray[ i ] = Double.parseDouble(line[i].trim());
                    }

          b.close();
          fis.close();
           }

           catch ( Exception e1 )
               {
                }
     }

    //creates labels, buttons and textfields
    public final void init() {
        Mortgage5Layout customLayout = new Mortgage5Layout();

        Container con = getContentPane();
        con.setLayout(customLayout);

        con.setFont(new Font("Arial", Font.PLAIN, 12));
        con.setLayout(customLayout);

        Llabel = new JLabel("Mortgage Loan Amount");//amount label
        con.add(Llabel);

        Ltextfield = new JTextField("");//amount textfield
        con.add(Ltextfield);

        Olabel = new JLabel("Preset Term & Interest Rate %");//option label
        con.add(Olabel);

        options = new JComboBox();
        con.add(options);

        options.addItem(" (choose rate)");
        options.addItem("7 years at 5.35%");
        options.addItem("15 years at 5.5%");
        options.addItem("30 years at 5.75%");

        Tlabel = new JLabel("Term (years)");//term label
        con.add(Tlabel);

        Ttextfield = new JTextField("");//term textfield
        con.add(Ttextfield);

        Rlabel = new JLabel("Interest Rate");//rate label
        con.add(Rlabel);

        Rtextfield = new JTextField("");//rate textfield
        con.add(Rtextfield);

        Plabel = new JLabel("Monthly Payment Amount");//payment label
        con.add(Plabel);

        $label = new JLabel("");//payment textfield
        con.add($label);

        calculate = new JButton("Calculate");//calculate button
        con.add(calculate);
        calculate.setBackground(Color.green);

        reset = new JButton("Reset");//reset button
        con.add(reset);
        reset.setBackground(Color.yellow);

        end = new JButton("End");//end button
        con.add(end);
        end.setBackground(Color.red);

        //table header names
        String[] columnNames = {"Payment #", "Payment Amount", "Interest", "Principle Reduction",
            "Remaining Balance"};

        //create table and table model
        model = new DefaultTableModel(columnNames, 0);
        table = new JTable(model);
        JScrollPane scroll = new JScrollPane(table);
        table.setPreferredScrollableViewportSize(new Dimension(10, 600));
        con.add(scroll);

        graph = new JButton("Display Graph");//Display Graph button
        con.add(graph);
        graph.setBackground(Color.orange);

        //action listeners
        Ltextfield.addActionListener(this); //loanfield
        options.addActionListener(this); //interestfield
        calculate.addActionListener(this);  //calButtion
        reset.addActionListener(this); //resetButton
        end.addActionListener(this);  //endButton
        graph.addActionListener(this);  //graphButton
    }

    //action event from listeners
    public void actionPerformed(ActionEvent event) {
        Object source = event.getSource();
        if (source == calculate) {
            startCalculations();
        }

        if (source == reset) {
            reset();
        }

        if (source == options) {
            setRate();
        }

        if (source == end) {
            exit();
        }

        if (source == mnuExit) {
            exitGraph();
        }
        if (source == graph) {
            mFrame = new JFrame("Mortgage Graph");
            mFrame.getContentPane().add(new GraphPanel(yearlyPrinciple, yearlyInterest));
            mFrame.setSize(800, 600);
            mFrame.setLocation(200, 100);

            //trying to create menu
            // Create an instance of the menu (Creates the Menu Bar)
            JMenuBar mnuBar = new JMenuBar();
            mFrame.setJMenuBar(mnuBar);

            // Construct and populate the Exit menu (Creates the Exit Menu)
            JMenu mnuExitbar = new JMenu("End", true);
            mnuBar.add(mnuExitbar);
            mnuExitbar.add(mnuExit);

            mFrame.setVisible(true);

            //exit listener
            mnuExit.addActionListener(this);  //exitButton
        }
    }
    public JFrame mFrame = new JFrame();

    void exitGraph() {

        mFrame.dispose();
        mFrame = null;
    }

    void setRate() {
        int index = options.getSelectedIndex();

        //term and interest error check
        if (index > 0) {
            try {
                Ttextfield.setText(Integer.toString(trmArray[index - 1]));
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "Invalid or missing Loan Term.  Please try again!",
                        "Message Dialog", JOptionPane.PLAIN_MESSAGE);
                Ttextfield.setText(null);
            }

            try {
                Rtextfield.setText(Double.toString(intrstArray[index - 1]));
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null, "Invalid or missing Interest Rate.  Please try again!",
                        "Message Dialog", JOptionPane.PLAIN_MESSAGE);
                Rtextfield.setText(null);
            }
        }
    }

    //calculation section
    void startCalculations() {
        Thread thisThread = Thread.currentThread();
        NumberFormat currency = NumberFormat.getCurrencyInstance();

        double amt = 0;
        double trm = 0;
        double intrst = 0;
        double moIn = 0;
        double moTrm = 0;
        double prin = 0;
        double paymt = 0;

        //amount error check
        try {
            amt = Double.parseDouble(Ltextfield.getText());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Missing Amount or Use of Commas",
                    "Message Dialog", JOptionPane.PLAIN_MESSAGE);
            Ltextfield.setText(null);
            Ttextfield.setText(null);
            Rtextfield.setText(null);
            options.setSelectedIndex(0);
        }

        //term and interest error check
        try {
            trm = Double.parseDouble(Ttextfield.getText());

        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Invalid or missing Loan Term.  Please try again!",
                    "Message Dialog", JOptionPane.PLAIN_MESSAGE);
            Ttextfield.setText(null);
        }

        try {
            intrst = Double.parseDouble(Rtextfield.getText());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Invalid or missing Interest Rate.  Please try again!",
                    "Message Dialog", JOptionPane.PLAIN_MESSAGE);
            Rtextfield.setText(null);
        }

        if (amt > 0) {
            amt = Double.parseDouble(Ltextfield.getText());
            moIn = (intrst / 1200);//monthly interest rate
            moTrm = trm * 12;//number of payments
            paymt = (amt * moIn) / (1 - Math.pow((1 + moIn), -moTrm));//amount forumla
            yearlyPrinciple = new float[(int) trm]; // initialize the arrays to store yearly principle and interest
            yearlyInterest = new float[(int) trm];

            $label.setText("" + currency.format(paymt));

            double newPrin = amt;

            for (int i = 0; i < trm; i++) {
                yearlyInterest[i] = 0.0f; //start at 0.0
                yearlyPrinciple[i] = 0.0f; //start at 0.0
                for (int j = 1; j <= 12; j++) {
                    double newIn = moIn * newPrin;//monthly interest amount
                    double reduct = paymt - newIn;//monthly principle
                    yearlyInterest[i] += newIn; // accumalate the interest
                    yearlyPrinciple[i] += reduct; //accumalate the principle
                    newPrin -= reduct;//balance

                    //inserts different amounts into the table
                    model.addRow(new Object[]{Integer.toString((i * 12) + j), currency.format(paymt),
                                currency.format(newIn), currency.format(reduct), currency.format(newPrin)});
                }
                //for testing purposes only
//                         model.addRow(new Object[] { Integer.toString(i), currency.format(0.0),
//                    currency.format(yearlyInterest[i]), currency.format(yearlyPrinciple[i]), currency.format(0.0) });
            }
        }

        //less than 0 error check
        if (amt < 0) {
            JOptionPane.showMessageDialog(null, "Please Enter Positive Numbers Only.",
                    "Message Dialog", JOptionPane.PLAIN_MESSAGE);
            Ltextfield.setText(null);
        }

    }

    //resets all fields
    void reset() {
        Ltextfield.setText(null);
        Ttextfield.setText(null);
        Rtextfield.setText(null);
        options.setSelectedIndex(0);
        $label.setText(null);
        model.setRowCount(0);
    }

    //exit the program with thank you message
    void exit() {
        JOptionPane.showMessageDialog(null, "          Goodbye",
                "Message Dialog", JOptionPane.PLAIN_MESSAGE);

        System.exit(0);
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new mortgagecalculatorprogram7().setVisible(true);
            }
        });
    }
}

//creates class for container layout and placement
class Mortgage5Layout implements LayoutManager {

    public Mortgage5Layout() {
    }

    public void addLayoutComponent(String name, Component comp) {
    }

    public void removeLayoutComponent(Component comp) {
    }

    public Dimension preferredLayoutSize(Container parent) {
        Dimension dim = new Dimension(0, 0);
        Insets insets = parent.getInsets();
        dim.width = 600 + insets.left + insets.right;
        dim.height = 425 + insets.top + insets.bottom;

        return dim;
    }

    public Dimension minimumLayoutSize(Container parent) {
        Dimension dim = new Dimension(0, 0);

        return dim;
    }

    public void layoutContainer(Container parent) {
        Insets insets = parent.getInsets();

        Component c;
        c = parent.getComponent(0);
        if (c.isVisible()) {
            c.setBounds(insets.left + 8, insets.top + 8, 250, 24);
        }
        c = parent.getComponent(1);
        if (c.isVisible()) {
            c.setBounds(insets.left + 300, insets.top + 8, 175, 24);
        }
        c = parent.getComponent(2);
        if (c.isVisible()) {
            c.setBounds(insets.left + 8, insets.top + 40, 250, 24);
        }
        c = parent.getComponent(3);
        if (c.isVisible()) {
            c.setBounds(insets.left + 300, insets.top + 40, 150, 24);
        }
        c = parent.getComponent(4);
        if (c.isVisible()) {
            c.setBounds(insets.left + 8, insets.top + 72, 250, 24);
        }
        c = parent.getComponent(5);
        if (c.isVisible()) {
            c.setBounds(insets.left + 300, insets.top + 72, 96, 24);
        }
        c = parent.getComponent(6);
        if (c.isVisible()) {
            c.setBounds(insets.left + 8, insets.top + 104, 250, 24);
        }
        c = parent.getComponent(7);
        if (c.isVisible()) {
            c.setBounds(insets.left + 300, insets.top + 104, 112, 24);
        }
        c = parent.getComponent(8);
        if (c.isVisible()) {
            c.setBounds(insets.left + 8, insets.top + 136, 250, 24);
        }
        c = parent.getComponent(9);
        if (c.isVisible()) {
            c.setBounds(insets.left + 300, insets.top + 136, 112, 24);
        }
        c = parent.getComponent(10);
        if (c.isVisible()) {
            c.setBounds(insets.left + 50, insets.top + 168, 96, 24);
        }
        c = parent.getComponent(11);
        if (c.isVisible()) {
            c.setBounds(insets.left + 225, insets.top + 168, 112, 24);
        }
        c = parent.getComponent(12);
        if (c.isVisible()) {
            c.setBounds(insets.left + 400, insets.top + 168, 96, 24);
        }
        c = parent.getComponent(13);
        if (c.isVisible()) {
            c.setBounds(insets.left + 8, insets.top + 200, 575, 160);
        }
        c = parent.getComponent(14);
        if (c.isVisible()) {
            c.setBounds(insets.left + 225, insets.top + 375, 112, 24);
        }
    }
}

class GraphPanel extends JPanel {

    final int HPAD = 60,
            VPAD = 40;
    int[] data;
    Font font;
    float[] principleData;
    float[] interestData;

    public GraphPanel(float[] p, float[] i) {

        principleData = p;
        interestData = i;

        font = new Font("lucida sans regular", Font.PLAIN, 16);
        setBackground(Color.white);
    }
}



//Code for Graph

package mortgagecalculatorprogram7;

// Program draws a bar chart.
import java.awt.*;
import javax.swing.*;

public class Chart extends JFrame {
    //stores the number of yeras

    private int years;

    // constructor
    public Chart(int years) {
//sets title for the window
        super("Mortgage Payment Calculator Chart");

        this.years = years;


        // sets the size of the window for visiblility
        setSize(1000, 800);
        setVisible(true);

    }

    // Draw chart
    // The method 'paint' will be executed right away after the constructor.
    @Override
    public void paint(Graphics g) {
        super.paint(g);

        // creates a 2D object to draw
        Graphics2D g2d = (Graphics2D) g;

        // set color and draw the bar for the first quarter sales
        g2d.setColor(Color.blue);
        g2d.drawLine(110, 30, 110, 655);
        g2d.drawLine(110, 655, 1015, 655);
        g2d.setFont(new Font("Font.PLAIN", Font.PLAIN, 18));
        g2d.drawString("A", 10, 150);
        g2d.drawString("M", 7, 170);
        g2d.drawString("O", 7, 190);
        g2d.drawString("U", 7, 210);
        g2d.drawString("N", 7, 230);
        g2d.drawString("T", 7, 250);

        int amount = 200000;
        int line = 55;
        for (int i = 0; i < 660; i += 60) {

            g2d.drawString("$" + amount, 30, 60 + i);
            g2d.drawLine(105, line + i, 115, line + i);

            amount -= 20000;

        }
        g2d.drawString("Y E A R S ", 500, 690);

        if (years == 30) {
            int count = 0;
            for (int i = 0; i <= 990; i += 30) {
                g2d.drawString("" + count, 107 + i, 675);
                g2d.drawLine(110 + i, 650, 110 + i, 660);
                count++;
            }
            g2d.setColor(Color.red);

            g2d.drawLine(110, 30, 1010, 655);
        } else if (years == 20) {
            int count = 0;
            for (int i = 0; i <= 990; i += 45) {
                g2d.drawString("" + count, 107 + i, 675);
                g2d.drawLine(110 + i, 650, 110 + i, 660);
                count++;
            }
            g2d.setColor(Color.red);

            g2d.drawLine(110, 55, 1010, 655);
        } else if (years == 15) {
            int count = 0;
            for (int i = 0; i <= 990; i += 60) {
                g2d.drawString("" + count, 107 + i, 675);
                g2d.drawLine(110 + i, 650, 110 + i, 660);
                count++;
            }
            g2d.setColor(Color.red);

            g2d.drawLine(110, 55, 1010, 655);
        } else if (years == 10) {
            int count = 0;
            for (int i = 0; i <= 990; i += 90) {
                g2d.drawString("" + count, 107 + i, 675);
                g2d.drawLine(110 + i, 650, 110 + i, 660);
                count++;
            }
            g2d.setColor(Color.red);

            g2d.drawLine(110, 55, 1010, 655);
        } else if (years == 7) {
            int count = 0;
            for (int i = 0; i <= 990; i += 120) {
                g2d.drawString("" + count, 107 + i, 675);
                g2d.drawLine(110 + i, 650, 110 + i, 660);
                count++;
            }
            g2d.setColor(Color.red);

            g2d.drawLine(110, 55, 950, 655);
        }

        g2d.setFont(new Font("Font.BOLD", Font.PLAIN, 24));
        g2d.drawString("Mortgage Payment Calculator Chart", 300, 50);

        
    }
}

Attached File(s)


This post has been edited by Dogstopper: 07 September 2010 - 08:45 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Mortgage Payment Calculator

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon

Reputation: 2965
  • View blog
  • Posts: 11,222
  • Joined: 15-July 08

Re: Mortgage Payment Calculator

Posted 07 September 2010 - 08:46 PM

Alright, next time, please post your code in the code tags: --> :code:

Could you also provide us the error message?
Was This Post Helpful? 0
  • +
  • -

#3 Palo726  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 18-August 10

Re: Mortgage Payment Calculator

Posted 07 September 2010 - 09:14 PM

View PostDogstopper, on 07 September 2010 - 07:46 PM, said:

Alright, next time, please post your code in the code tags: --> :code:

Could you also provide us the error message?


The program is throwing my error message under the comment section (//term and interest error check). When I select from the list and leave the loan term and interest rate fields empty it throws my NumberFormatException.

This is what NetBeans returns...

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at mortgagecalculatorprogram7.mortgagecalculatorprogram7.setRate(mortgagecalculatorprogram7.java:262)
at mortgagecalculatorprogram7.mortgagecalculatorprogram7.actionPerformed(mortgagecalculatorprogram7.java:216)
at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1240)
at javax.swing.JComboBox.setSelectedItem(JComboBox.java:567)
at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:603)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:817)
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:273)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:481)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.window.dispatchEventImpl(window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Was This Post Helpful? 0
  • +
  • -

#4 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Mortgage Payment Calculator

Posted 07 September 2010 - 10:37 PM

You never call public final void load() { so int[] trmArray; is never initialized. Hence the statement Ttextfield.setText(Integer.toString(trmArray[index - 1])); is referencing a null object.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1