Mortgage calculator request #7 help

  • (2 Pages)
  • +
  • 1
  • 2

28 Replies - 2281 Views - Last Post: 11 September 2011 - 01:59 PM Rate Topic: -----

#1 falloncade  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 17-July 11

Mortgage calculator request #7 help

Posted 10 September 2011 - 06:14 PM

I am having some serious issues with my coding on this mortgage calculator assignment. Could someone please take a look and help me figure this out? Thanks!!
package mortgagecalcufinal;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Line2D;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
	 
	public final class Mortgagecalcufinal extends JFrame implements ActionListener {
	    JLabel Llabel;
	    JTextField Ltextfield;
	    JLabel Olabel;
	    JComboBox options;
	    JLabel Tlabel;
	    JTextField Ttextfield;
	    JLabel Rlabel;
	    JTextField Rtextfield;
	    JLabel Plabel;
	    JLabel $label;
	    JButton calculate;
	    JButton reset;
	    JButton end;
	    JTable table;
	    JMenuItem mnuExit = new JMenuItem("Exit");
	    DefaultTableModel model;
	double[][] trmAndIntrstArray;
	    JButton graph;
	    private float[] yearlyPrinciple;
	    private float[] yearlyInterest;
	 
	    // Title
	    public Mortgagecalcufinal() {
	        super("Gene Day Week 5");
	        setDefaultLookAndFeelDecorated(true);
	        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	        load();
	        init();
	        pack();
	        setVisible(true);
	    }
	 
	    // Pull info from file
	 
	    public void load() {
	        Reader fis;
	        try {
	 
	            fis = new FileReader("loandata.txt");
	 
	            BufferedReader b = new BufferedReader(fis);
	            String inputholder = "";
	            String termsandrates = "";
	            while ((inputholder = b.readLine()) != null) {
	                termsandrates = termsandrates + inputholder + "|";
	            }
	            String[] line = termsandrates.split("[|]");
	            trmAndIntrstArray = new double[line.length][2];
	            for (int i = 0; i < line.length; i++) {
	                String[] lineValues = line[i].split(",");
	                if (lineValues.length == 2) {
	                    trmAndIntrstArray[i][0] = Double.parseDouble(lineValues[0]
	                            .trim());
	                    trmAndIntrstArray[i][1] = Double.parseDouble(lineValues[1]
	                            .trim());
	                }
	            }
	 
	            b.close();
	            fis.close();
	        }
	 
	        catch (Exception e1) {
	        }
	    }
	 
	    // labels, buttons and textfields
	 
	    public void init() {
	        MortgagecalcufinalLayout customLayout = new MortgagecalcufinalLayout();
	 
	        Container con = getContentPane();
	        con.setLayout(customLayout);
	 
	        con.setFont(new Font("Arial", Font.PLAIN, 12));
	        con.setLayout(customLayout);
	 
	        Llabel = new JLabel("Mortgage Loan Amount $ (no comma)");
	        con.add(Llabel);
	 
	        Ltextfield = new JTextField("");
	        con.add(Ltextfield);
	 
	        Olabel = new JLabel("Term & Interest Rate %");
	        con.add(Olabel);
	 
	        options = new JComboBox();
	        con.add(options);
	        options.addItem(" (Preset rate)");
	 
	        for (double[] trmAndIntrst : trmAndIntrstArray) {
	            options.addItem(trmAndIntrst[0] + " years at " + trmAndIntrst[1] + "%");
	        }
	 
	        Tlabel = new JLabel("Term (years)");
	        con.add(Tlabel);
	 
	        Ttextfield = new JTextField("");
	        con.add(Ttextfield);
	 
	        Rlabel = new JLabel("Interest Rate");
	        con.add(Rlabel);
	 
	        Rtextfield = new JTextField("");
	        con.add(Rtextfield);
	 
	        Plabel = new JLabel("Monthly Payment Amount");
	        con.add(Plabel);
	 
	        $label = new JLabel("");
	        con.add($label);
	 
	        calculate = new JButton("Calculate");
	        con.add(calculate);
	        calculate.setBackground(Color.white);
	 
	        reset = new JButton("Clear");
	        con.add(reset);
	        reset.setBackground(Color.white);
	 
	        end = new JButton("End");
	        con.add(end);
	        end.setBackground(Color.white);
	 
	        // 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("See Graph");
	        con.add(graph);
	        graph.setBackground(Color.white);
	 
	        // action listeners
	        Ltextfield.addActionListener(this);
	        options.addActionListener(this);
	        calculate.addActionListener(this);
	        reset.addActionListener(this);
	        end.addActionListener(this);
	        graph.addActionListener(this);
	    }
	 
	    // action event from listeners
    @Override
	    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(720, 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);
	        }
	    }
	 
	    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(Double.toString(trmAndIntrstArray[index - 1][0]));
	            }
	 
	            catch (NumberFormatException e) {
	                JOptionPane.showMessageDialog(null,
	                        "Invalid or missing Loan Term.  Please try again!",
	                        "Error", JOptionPane.PLAIN_MESSAGE);
	                Ttextfield.setText(null);
	            }
	 
	            try {
	                Rtextfield.setText(Double.toString(trmAndIntrstArray[index - 1][1]));
	            }
	 
	            catch (NumberFormatException e) {
	                JOptionPane.showMessageDialog(null, "Invalid. try again!",
	                        "Error", 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", "Error",
	                    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,
	                    "missing Loan Term.  Please try again!", "Error",
	                    JOptionPane.PLAIN_MESSAGE);
	            Ttextfield.setText(null);
	        }
	 
	        try {
	            intrst = Double.parseDouble(Rtextfield.getText());
	        }
	 
	        catch (NumberFormatException e) {
	            JOptionPane.showMessageDialog(null,
	                    "missing Interest Rate.  Please try again!", "Error",
	                    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;
	                model.setRowCount(0);
	 
	            for (int i = 0; i < trm; i++) {
	                yearlyInterest[i] = 0.0f;
	                yearlyPrinciple[i] = 0.0f;
	                for (int j = 1; j <= 12; j++) {
	                    double newIn = moIn * newPrin;
	                    double reduct = paymt - newIn;
	                    yearlyInterest[i] += newIn;
	                    yearlyPrinciple[i] += reduct;
	                    newPrin = newPrin - reduct;
	 
	                    if (newPrin < 0)
	                        newPrin = 0;
	                    else
	                        newPrin = newPrin;
	 
	                    model
	                            .addRow(new Object[] {
	                                    Integer.toString((i * 12) + j),
	                                    currency.format(paymt),
	                                    currency.format(newIn),
	                                    currency.format(reduct),
	                                    currency.format(newPrin) });
	                }
	 
	                // 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 Positie 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, "         Thank you ",
	                "Message Dialog", JOptionPane.PLAIN_MESSAGE);
	 
	        System.exit(0);
	    }
	 
	    public static void main(String args[]) {
	        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
	            public void run() {
	                new Mortgagecalcufinal().setVisible(true);
	            }
	        });
	    }
	}
	 
	// creates class for container layout and placement
	class MortgagecalcufinalLayout implements LayoutManager {
	    public MortgagecalcufinalLayout() {
	    }
	 
    @Override
	    public void addLayoutComponent(String name, Component comp) {
	    }
	 
    @Override
	    public void removeLayoutComponent(Component comp) {
	    }
	 
    @Override
	    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;
	    }
	 
    @Override
	    public Dimension minimumLayoutSize(Container parent) {
	        Dimension dim = new Dimension(0, 0);
	 
	        return dim;
	    }
	 
    @Override
	    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;
    private int canvasWidth;
    private int verticalPadding;
    private int canvasHeight;
	 
	    public GraphPanel(float[] p, float[] i) {
	 
	        principleData = p;
	        interestData = i;
	 
	        font = new Font("lucida sans regular", Font.PLAIN, 16);
	        setBackground(Color.white);
	    }
	 
    @Override
	    protected void paintComponent(Graphics g) {
	        super.paintComponent(g);
	 
	        Graphics2D g2 = (Graphics2D) g;
	        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
	                RenderingHints.VALUE_ANTIALIAS_ON);
	        g2.setFont(font);
	        FontRenderContext frc = g2.getFontRenderContext();
	        int w = getWidth();
	        int h = getHeight();
	        // scales
	        float xInc = (w - HPAD - VPAD) / (interestData.length - 1);// 11f;
	        float yInc = (h - 2 * VPAD) / 10f;
	        int[] dataVals = getDataVals(); // min and max values for y-axis
	        float yScale = dataVals[2] / 10f;
	 
	        // ordinate (y - axis)
	        g2.draw(new Line2D.Double(HPAD, VPAD, HPAD, h - VPAD));
	        // plot tic marks
	        float x1 = HPAD, y1 = VPAD, x2 = HPAD - 3, y2;
	        for (int j = 0; j < 10; j++) {
	            g2.draw(new Line2D.Double(x1, y1, x2, y1));
	            y1 += yInc;
	        }
	        // labels
	        String text;
	        LineMetrics lm;
	        float xs, ys, textWidth, height;
	        for (int j = 0; j <= 10; j++) {
	            text = String.valueOf(dataVals[1] - (int) (j * yScale));
	            textWidth = (float) font.getStringBounds(text, frc).getWidth();
	            lm = font.getLineMetrics(text, frc);
	            height = lm.getAscent();
	            xs = HPAD - textWidth - 7;
	            ys = VPAD + (j * yInc) + height / 2;
	            g2.drawString(text, xs, ys);
	            g2.drawString.(Color.RED);
	            g2.drawString("Payment", 5, 15);
	                g2.drawString("Number of Years", canvasWidth/3 , canvasHeight - verticalPadding/10);
	        }
	 
	        // abcissa (x - axis)
	        g2.draw(new Line2D.Double(HPAD, h - VPAD, w - VPAD, h - VPAD));
	        // tic marks
	        x1 = HPAD;
	        y1 = h - VPAD;
	        y2 = y1 + 3;
	        for (int j = 0; j < interestData.length; j++) {
	            g2.draw(new Line2D.Double(x1, y1, x1, y2));
	            x1 += xInc;
	        }
	        // labels
	        ys = h - VPAD;
	        for (int j = 0; j < interestData.length; j++) {
	            text = String.valueOf(j + 1);
	            textWidth = (float) font.getStringBounds(text, frc).getWidth();
	            lm = font.getLineMetrics(text, frc);
	            height = lm.getHeight();
	            xs = HPAD + j * xInc - textWidth / 2;
	            g2.drawString(text, xs, ys + height);
	        }
	 
	        // plot data
	        float yy2 = 0, yy1 = 0, xx2 = 0, xx1;
	        x1 = HPAD;
	        xx1 = HPAD;
	        yScale = (float) (h - 2 * VPAD) / dataVals[2];
	 
	        for (int j = 0; j < interestData.length; j++) {
	            g.setColor(Color.blue);
	            y1 = VPAD + (h - 2 * VPAD) - (principleData[j] - dataVals[0])
	                    * yScale;
	 
	            if (j > 0)
	                g2.draw(new Line2D.Double(x1, y1, x2, y2));
	            x2 = x1;
	            y2 = y1;
	            x1 += xInc;
	 
	            g.setColor(Color.red);
	            yy1 = VPAD + (h - 2 * VPAD) - (interestData[j] - dataVals[0])
	                    * yScale;
	            if (j > 0)
	                g2.draw(new Line2D.Double(xx1, yy1, xx2, yy2));
	            xx2 = xx1;
	            yy2 = yy1;
	            xx1 += xInc;
	 
	        }
	    }
	 
	    private int[] getDataVals() {
	        int max = Integer.MIN_VALUE;
	        int min = Integer.MAX_VALUE;
	        int j = interestData.length - 1;
	        max = (int) principleData[j];
	        min = (int) interestData[j];
	        int span = max - min;
	        return new int[] { min, max, span };
	    }
	}


Is This A Good Question/Topic? 0
  • +

Replies To: Mortgage calculator request #7 help

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 06:16 PM

What problems are you having? Include any error messages, cut and paste.
Was This Post Helpful? 0
  • +
  • -

#3 falloncade  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 17-July 11

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 06:16 PM

By the way, like a putz I forgot the error so here it is. its on line 558:

C:\Users\Falloncade\Documents\NetBeansProjects\mortgagecalcufinal\src\mortgagecalcufinal\Mortgagecalcufinal.java:558: <identifier> expected
g2.drawString.(Color.RED);
^
1 error
Was This Post Helpful? 0
  • +
  • -

#4 giggly kisses  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 81
  • View blog
  • Posts: 391
  • Joined: 29-March 09

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 06:25 PM

That error is because on line 557 you a period in between your method call and the parenthesis for the parameters.

g2.drawString.(Color.RED);
                    ^



EDIT: The arrow is pointing at the wrong period because of how the code tag spaces things. The period you need to remove is the one in between drawString and ().

This post has been edited by giggly kisses: 10 September 2011 - 06:30 PM

Was This Post Helpful? 0
  • +
  • -

#5 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 06:28 PM

GigglyKisses' fix won't completely solve the problem. That's still an illegal method call, so you'll need to figure out what you're trying to do there and find the right method for it.
Was This Post Helpful? 1
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12218
  • View blog
  • Posts: 45,291
  • Joined: 27-December 08

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 06:48 PM

You cannot draw a color using the drawString() method. The drawString() method is to draw text onto the JComponent. You need to setColor() on your Graphics if you want to change the color, then drawString().
Was This Post Helpful? 0
  • +
  • -

#7 falloncade  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 17-July 11

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 07:47 PM

View Postmacosxnerd101, on 10 September 2011 - 06:48 PM, said:

You cannot draw a color using the drawString() method. The drawString() method is to draw text onto the JComponent. You need to setColor() on your Graphics if you want to change the color, then drawString().


I changed the line to g2.setColor(color.red); which seems to have worked because the program compiled. But now When I run the application absolutely nothing happens. I am so lost. I have to get this done tomorrow at latest because I start a new job on Monday and won't be home enough time to finish. Here is the errors I receive when I run the application:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at mortgagecalcufinal.Mortgagecalcufinal.init(Mortgagecalcufinal.java:127)
at mortgagecalcufinal.Mortgagecalcufinal.<init>(Mortgagecalcufinal.java:64)
at mortgagecalcufinal.Mortgagecalcufinal$1.run(Mortgagecalcufinal.java:398)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
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)
BUILD SUCCESSFUL (total time: 3 seconds)

package mortgagecalcufinal;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Line2D;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
	 
	public final class Mortgagecalcufinal extends JFrame implements ActionListener {
	    JLabel Llabel;
	    JTextField Ltextfield;
	    JLabel Olabel;
	    JComboBox options;
	    JLabel Tlabel;
	    JTextField Ttextfield;
	    JLabel Rlabel;
	    JTextField Rtextfield;
	    JLabel Plabel;
	    JLabel $label;
	    JButton calculate;
	    JButton reset;
	    JButton end;
	    JTable table;
	    JMenuItem mnuExit = new JMenuItem("Exit");
	    DefaultTableModel model;
	double[][] trmAndIntrstArray;
	    JButton graph;
	    private float[] yearlyPrinciple;
	    private float[] yearlyInterest;
	 
	    // Title
	    public Mortgagecalcufinal() {
	        super("Gene Day Week 5");
	        setDefaultLookAndFeelDecorated(true);
	        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	        load();
	        init();
	        pack();
	        setVisible(true);
	    }
	 
	    // Pull info from file
	 
	    public void load() {
	        Reader fis;
	        try {
	 
	            fis = new FileReader("loandata.txt");
	 
	            BufferedReader b = new BufferedReader(fis);
	            String inputholder = "";
	            String termsandrates = "";
	            while ((inputholder = b.readLine()) != null) {
	                termsandrates = termsandrates + inputholder + "|";
	            }
	            String[] line = termsandrates.split("[|]");
	            trmAndIntrstArray = new double[line.length][2];
	            for (int i = 0; i < line.length; i++) {
	                String[] lineValues = line[i].split(",");
	                if (lineValues.length == 2) {
	                    trmAndIntrstArray[i][0] = Double.parseDouble(lineValues[0]
	                            .trim());
	                    trmAndIntrstArray[i][1] = Double.parseDouble(lineValues[1]
	                            .trim());
	                }
	            }
	 
	            b.close();
	            fis.close();
	        }
	 
	        catch (Exception e1) {
	        }
	    }
	 
	    // labels, buttons and textfields
	 
	    public void init() {
	        MortgagecalcufinalLayout customLayout = new MortgagecalcufinalLayout();
	 
	        Container con = getContentPane();
	        con.setLayout(customLayout);
	 
	        con.setFont(new Font("Arial", Font.PLAIN, 12));
	        con.setLayout(customLayout);
	 
	        Llabel = new JLabel("Mortgage Loan Amount $ (no comma)");
	        con.add(Llabel);
	 
	        Ltextfield = new JTextField("");
	        con.add(Ltextfield);
	 
	        Olabel = new JLabel("Term & Interest Rate %");
	        con.add(Olabel);
	 
	        options = new JComboBox();
	        con.add(options);
	        options.addItem(" (Preset rate)");
	 
	        for (double[] trmAndIntrst : trmAndIntrstArray) {
	            options.addItem(trmAndIntrst[0] + " years at " + trmAndIntrst[1] + "%");
	        }
	 
	        Tlabel = new JLabel("Term (years)");
	        con.add(Tlabel);
	 
	        Ttextfield = new JTextField("");
	        con.add(Ttextfield);
	 
	        Rlabel = new JLabel("Interest Rate");
	        con.add(Rlabel);
	 
	        Rtextfield = new JTextField("");
	        con.add(Rtextfield);
	 
	        Plabel = new JLabel("Monthly Payment Amount");
	        con.add(Plabel);
	 
	        $label = new JLabel("");
	        con.add($label);
	 
	        calculate = new JButton("Calculate");
	        con.add(calculate);
	        calculate.setBackground(Color.white);
	 
	        reset = new JButton("Clear");
	        con.add(reset);
	        reset.setBackground(Color.white);
	 
	        end = new JButton("End");
	        con.add(end);
	        end.setBackground(Color.white);
	 
	        // 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("See Graph");
	        con.add(graph);
	        graph.setBackground(Color.white);
	 
	        // action listeners
	        Ltextfield.addActionListener(this);
	        options.addActionListener(this);
	        calculate.addActionListener(this);
	        reset.addActionListener(this);
	        end.addActionListener(this);
	        graph.addActionListener(this);
	    }
	 
	    // action event from listeners
    @Override
	    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(720, 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);
	        }
	    }
	 
	    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(Double.toString(trmAndIntrstArray[index - 1][0]));
	            }
	 
	            catch (NumberFormatException e) {
	                JOptionPane.showMessageDialog(null,
	                        "Invalid or missing Loan Term.  Please try again!",
	                        "Error", JOptionPane.PLAIN_MESSAGE);
	                Ttextfield.setText(null);
	            }
	 
	            try {
	                Rtextfield.setText(Double.toString(trmAndIntrstArray[index - 1][1]));
	            }
	 
	            catch (NumberFormatException e) {
	                JOptionPane.showMessageDialog(null, "Invalid. try again!",
	                        "Error", 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", "Error",
	                    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,
	                    "missing Loan Term.  Please try again!", "Error",
	                    JOptionPane.PLAIN_MESSAGE);
	            Ttextfield.setText(null);
	        }
	 
	        try {
	            intrst = Double.parseDouble(Rtextfield.getText());
	        }
	 
	        catch (NumberFormatException e) {
	            JOptionPane.showMessageDialog(null,
	                    "missing Interest Rate.  Please try again!", "Error",
	                    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;
	                model.setRowCount(0);
	 
	            for (int i = 0; i < trm; i++) {
	                yearlyInterest[i] = 0.0f;
	                yearlyPrinciple[i] = 0.0f;
	                for (int j = 1; j <= 12; j++) {
	                    double newIn = moIn * newPrin;
	                    double reduct = paymt - newIn;
	                    yearlyInterest[i] += newIn;
	                    yearlyPrinciple[i] += reduct;
	                    newPrin = newPrin - reduct;
	 
	                    if (newPrin < 0)
	                        newPrin = 0;
	                    else
	                        newPrin = newPrin;
	 
	                    model
	                            .addRow(new Object[] {
	                                    Integer.toString((i * 12) + j),
	                                    currency.format(paymt),
	                                    currency.format(newIn),
	                                    currency.format(reduct),
	                                    currency.format(newPrin) });
	                }
	 
	                // 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 Positie 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, "         Thank you ",
	                "Message Dialog", JOptionPane.PLAIN_MESSAGE);
	 
	        System.exit(0);
	    }
	 
	    public static void main(String args[]) {
	        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
	            public void run() {
	                new Mortgagecalcufinal().setVisible(true);
	            }
	        });
	    }
	}
	 
	// creates class for container layout and placement
	class MortgagecalcufinalLayout implements LayoutManager {
	    public MortgagecalcufinalLayout() {
	    }
	 
    @Override
	    public void addLayoutComponent(String name, Component comp) {
	    }
	 
    @Override
	    public void removeLayoutComponent(Component comp) {
	    }
	 
    @Override
	    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;
	    }
	 
    @Override
	    public Dimension minimumLayoutSize(Container parent) {
	        Dimension dim = new Dimension(0, 0);
	 
	        return dim;
	    }
	 
    @Override
	    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;
    private int canvasWidth;
    private int verticalPadding;
    private int canvasHeight;
	 
	    public GraphPanel(float[] p, float[] i) {
	 
	        principleData = p;
	        interestData = i;
	 
	        font = new Font("lucida sans regular", Font.PLAIN, 16);
	        setBackground(Color.white);
	    }
	 
    @Override
	    protected void paintComponent(Graphics g) {
	        super.paintComponent(g);
	 
	        Graphics2D g2 = (Graphics2D) g;
	        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
	                RenderingHints.VALUE_ANTIALIAS_ON);
	        g2.setFont(font);
	        FontRenderContext frc = g2.getFontRenderContext();
	        int w = getWidth();
	        int h = getHeight();
	        // scales
	        float xInc = (w - HPAD - VPAD) / (interestData.length - 1);// 11f;
	        float yInc = (h - 2 * VPAD) / 10f;
	        int[] dataVals = getDataVals(); // min and max values for y-axis
	        float yScale = dataVals[2] / 10f;
	 
	        // ordinate (y - axis)
	        g2.draw(new Line2D.Double(HPAD, VPAD, HPAD, h - VPAD));
	        // plot tic marks
	        float x1 = HPAD, y1 = VPAD, x2 = HPAD - 3, y2;
	        for (int j = 0; j < 10; j++) {
	            g2.draw(new Line2D.Double(x1, y1, x2, y1));
	            y1 += yInc;
	        }
	        // labels
	        String text;
	        LineMetrics lm;
	        float xs, ys, textWidth, height;
	        for (int j = 0; j <= 10; j++) {
	            text = String.valueOf(dataVals[1] - (int) (j * yScale));
	            textWidth = (float) font.getStringBounds(text, frc).getWidth();
	            lm = font.getLineMetrics(text, frc);
	            height = lm.getAscent();
	            xs = HPAD - textWidth - 7;
	            ys = VPAD + (j * yInc) + height / 2;
	            g2.drawString(text, xs, ys);
	            g2.setColor(Color.RED);
	            g2.drawString("Payment", 5, 15);
	                g2.drawString("Number of Years", canvasWidth/3 , canvasHeight - verticalPadding/10);
	        }
	 
	        // abcissa (x - axis)
	        g2.draw(new Line2D.Double(HPAD, h - VPAD, w - VPAD, h - VPAD));
	        // tic marks
	        x1 = HPAD;
	        y1 = h - VPAD;
	        y2 = y1 + 3;
	        for (int j = 0; j < interestData.length; j++) {
	            g2.draw(new Line2D.Double(x1, y1, x1, y2));
	            x1 += xInc;
	        }
	        // labels
	        ys = h - VPAD;
	        for (int j = 0; j < interestData.length; j++) {
	            text = String.valueOf(j + 1);
	            textWidth = (float) font.getStringBounds(text, frc).getWidth();
	            lm = font.getLineMetrics(text, frc);
	            height = lm.getHeight();
	            xs = HPAD + j * xInc - textWidth / 2;
	            g2.drawString(text, xs, ys + height);
	        }
	 
	        // plot data
	        float yy2 = 0, yy1 = 0, xx2 = 0, xx1;
	        x1 = HPAD;
	        xx1 = HPAD;
	        yScale = (float) (h - 2 * VPAD) / dataVals[2];
	 
	        for (int j = 0; j < interestData.length; j++) {
	            g.setColor(Color.blue);
	            y1 = VPAD + (h - 2 * VPAD) - (principleData[j] - dataVals[0])
	                    * yScale;
	 
	            if (j > 0)
	                g2.draw(new Line2D.Double(x1, y1, x2, y2));
	            x2 = x1;
	            y2 = y1;
	            x1 += xInc;
	 
	            g.setColor(Color.red);
	            yy1 = VPAD + (h - 2 * VPAD) - (interestData[j] - dataVals[0])
	                    * yScale;
	            if (j > 0)
	                g2.draw(new Line2D.Double(xx1, yy1, xx2, yy2));
	            xx2 = xx1;
	            yy2 = yy1;
	            xx1 += xInc;
	 
	        }
	    }
	 
	    private int[] getDataVals() {
	        int max = Integer.MIN_VALUE;
	        int min = Integer.MAX_VALUE;
	        int j = interestData.length - 1;
	        max = (int) principleData[j];
	        min = (int) interestData[j];
	        int span = max - min;
	        return new int[] { min, max, span };
	    }
	}


Thanks you everyone so much!
Was This Post Helpful? 0
  • +
  • -

#8 falloncade  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 17-July 11

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 08:42 PM

I went and changed the entire coding. Can someone please go over the coding, see how the application runs for you and let me know what you think? Thanks.
package mortgagecalc10;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.io.*;
import java.awt.geom.*;
	 
	public class Mortgagecalc10 extends JFrame implements ActionListener {
	 
	    //Labels for Displaying information to the user
	    JLabel lblPrinciple = new JLabel("Enter loan amount: $ ");
	    JLabel lblPayment = new JLabel("Monthly Payment: $");
	    JLabel lblMonthly = new JLabel("0.00");
	    JLabel lblBlank = new JLabel("");
	    //Text feilds for entering and displaying desired data
	    JTextField txtPrinciple = new JTextField("0", 15);
	    //Text area for output of information
	    JTextArea txtInfo = new JTextArea(9, 25);
	    JScrollPane scrInfo = new JScrollPane(txtInfo);
	    //Buttons to select interest rate & term, exit and clear the form
	    JButton btnCalc = new JButton("Calculate");
	    JButton btnQuit = new JButton("Quit");
	    //Creates Array for the combobox and also creates the combobox
	    String[] strTerm = new String[3];
	    JComboBox cmbTerm = new JComboBox();
	    //Declare Variables
	    double dblTotIntPer = 0;
	    double dblInt = 0;
	    double dblIntDeg = 0;
	    int intTotInt = 0;
	    double dblTotPrin = 0;
	    double dblIntPaid = 0;
	    double dblLoanAndInt = 0;
	    int intPrin;
	    int intTotalInt;
	    Color Green = new Color(0xCC, 0xCC, 0x99);
	    Color Blue = new Color(0x33, 0xCC, 0xCC);
	    PiePanel pie = new PiePanel(2);
	 
	    public Mortgagecalc10() {
	        //create the main panels that willbe used for the program
	        super("Bingeman Mortgage Calculator CR7");
	        setSize(500, 700);
	        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	        setLayout(new GridLayout(4, 1));
	        JPanel pnlCalc = new JPanel();
	        JPanel pnlCalc1 = new JPanel();
	        JPanel pnlCalc2 = new JPanel();
	        pnlCalc.setLayout(new GridLayout(2, 2));
	        pnlCalc1.setLayout(new FlowLayout());
	        pnlCalc2.setLayout(new FlowLayout());
	        pie.setLayout(new FlowLayout());
	        /*add the labels, textboxes, combobox, buttons, and scroll boxes,
	        set the font, and add the items to the panels along with making the
	        panels visible*/
	        pnlCalc.add(lblPrinciple);
	        lblPrinciple.setFont(new Font("Times New Roman", Font.PLAIN, 18));
	        pnlCalc.add(txtPrinciple);
	        txtPrinciple.setFont(new Font("Times New Roman", Font.PLAIN, 18));
	        pnlCalc.add(cmbTerm);
	        getTermsFromFile();
	        cmbTerm.setFont(new Font("Times New Roman", Font.PLAIN, 18));
	        pnlCalc.add(lblBlank);
	        pnlCalc1.add(btnCalc);
	        btnCalc.setFont(new Font("Times New Roman", Font.PLAIN, 18));
	        btnCalc.addActionListener(this);
	        pnlCalc1.add(btnQuit);
	        btnQuit.setFont(new Font("Times New Roman", Font.PLAIN, 18));
	        btnQuit.addActionListener(this);
	        scrInfo.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	        pnlCalc2.add(scrInfo);
	        add(pnlCalc);
	        add(pnlCalc1);
	        add(pnlCalc2);
	        pie.addSlice(Green, intPrin);
	        pie.addSlice(Blue, intTotalInt);
	        add(pie);
	        getRootPane().setDefaultButton(btnCalc);
	        setLookAndFeel();
	        txtPrinciple.selectAll();
	        setVisible(true);
	    }
	 
	    private void setLookAndFeel() {
	        //setting the look and feel of the program
	        try {
	            UIManager.setLookAndFeel(
	                    UIManager.getSystemLookAndFeelClassName());
	            SwingUtilities.updateComponentTreeUI(this);
	        } catch (Exception e) {
	            System.err.println("Couldn't use the system "
	                    + "look and feel: " + e);
	        }
	    }
	 
	    private void getTermsFromFile() {
	        try {//populate the combobox with it's values
	            String strLine;
	 
	            BufferedReader stmTerms = new BufferedReader(new FileReader("LoanData.txt"));
	            for (int a = 0; a <= 2; a++) {
	                strLine = stmTerms.readLine();
	                strTerm[a] = strLine;
	                cmbTerm.addItem(strLine);
	            }
	        } catch (Exception ex) {
	            System.out.println(ex.toString());
	        }
	    }
	 
	    public static void main(String[] args) {
	        //creating the main window
	        Mortgagecalc10 nw = new Mortgagecalc10();
	    }
	 
    @Override
	    public void actionPerformed(ActionEvent evt) {
	        Object source = evt.getSource();
	        int intPrinciple = Integer.parseInt(txtPrinciple.getText());
	        double dblLoanBal = intPrinciple;
	        //performing the main functions of the program
	        if (source == btnCalc) {
	            //Create loop for determining which rate and term were selected
	            Object strAnswer = cmbTerm.getSelectedItem();
	            if (strAnswer.equals("7 years at 5.35%")) {
	                txtInfo.setText("");
	                //declare starting variables
	                double dblRate = 5.35;
	                int intTimeyrs = 7;
	                int intTerm = 84;
	                intTotInt = 0;
	                dblIntPaid = 0;
	                for (int i = 1; i <= intTerm; i++) {
	                    //determine the monthly rate and place in variable
	                    double dblMnthlyrate = dblRate / 12;
	                    //calculate time in months and place in a variable
	                    int intTimemnths = intTimeyrs * 12;
	                    //calculate the decimal form of the monthly rate and place in a variabl
	                    double dblRatedec = dblMnthlyrate / 100;
	                    double dblOneplusratedec = (1 + dblRatedec);
	                    //create the exponent for the payment calculation and place in variable
	                    double dblExponent = Math.pow(dblOneplusratedec, -intTimemnths);
	                    //calculate mortgage payment and place in a variable
	                    double dblPayment = intPrinciple / ((1 - dblExponent) / dblRatedec);
	                    dblIntPaid = (dblLoanBal * dblRatedec);
	                    dblLoanAndInt = dblLoanBal + dblIntPaid;
	                    dblLoanBal = dblLoanAndInt - dblPayment;
	                    intTotInt = intTotInt + (int)dblIntPaid;
	                    DecimalFormat money = new DecimalFormat("$0,000.00");
	                    txtInfo.append("Payment #" + i
	                            + "\nPayment" + (money.format(dblPayment))
	                            + "\nLoan Balance" + (money.format(dblLoanBal))
	                            + "\nInterest Paid" + (money.format(dblIntPaid))
	                            + "\n" + "\n");
	                }
	                intPrin = intPrinciple;
	                pie.clearSlices(); // reset slices array
	                pie.repaint();
	                pie.addSlice(Green, intPrin);
	                pie.addSlice(Blue, intTotInt);
	                pie.repaint();
	                intTotInt = 0;
	            } else if (strAnswer.equals("15 years at 5.5%")) {
	                txtInfo.setText("");
	                //declare starting variables
	                double dblRate = 5.5;
	                int intTimeyrs = 15;
	                int intTerm = 180;
	                intTotInt = 0;
	                dblIntPaid = 0;
	                for (int i = 1; i <= intTerm; i++) {
	                    //determine the monthly rate and place in variable
	                    double dblMnthlyrate = dblRate / 12;
	                    //calculate time in months and place in a variable
	                    int intTimemnths = intTimeyrs * 12;
	                    //calculate the decimal form of the monthly rate and place in a variabl
	                    double dblRatedec = dblMnthlyrate / 100;
	                    double dblOneplusratedec = (1 + dblRatedec);
	                    //create the exponent for the payment calculation and place in variable
	                    double dblExponent = Math.pow(dblOneplusratedec, -intTimemnths);
	                    //calculate mortgage payment and place in a variable
	                    double dblPayment = intPrinciple / ((1 - dblExponent) / dblRatedec);
	                    dblIntPaid = (dblLoanBal * dblRatedec);
	                    dblLoanAndInt = dblLoanBal + dblIntPaid;
	                    dblLoanBal = dblLoanAndInt - dblPayment;
	                    intTotInt = intTotInt + (int)dblIntPaid;
	                    DecimalFormat money = new DecimalFormat("$0,000.00");
	                    txtInfo.append("Payment #" + i
	                            + "\nPayment" + (money.format(dblPayment))
	                            + "\nLoan Balance" + (money.format(dblLoanBal))
	                            + "\nInterest Paid" + (money.format(dblIntPaid))
	                            + "\n" + "\n");
	                }
	                intPrin = intPrinciple;
	                pie.clearSlices(); // reset slices array
	                pie.repaint();
	                pie.addSlice(Green, intPrin);
	                pie.addSlice(Blue, intTotInt);
	                pie.repaint();
	                intTotInt = 0;
	            } else if (strAnswer.equals("30 years at 5.75%")) {
	                txtInfo.setText("");
	                //declare starting variables
	                double dblRate = 5.75;
	                int intTimeyrs = 30;
	                int intTerm = 360;
	                intTotInt = 0;
	                dblIntPaid = 0;
	                for (int i = 1; i <= intTerm; i++) {
	                    //determine the monthly rate and place in variable
	                    double dblMnthlyrate = dblRate / 12;
	                    //calculate time in months and place in a variable
	                    int intTimemnths = intTimeyrs * 12;
	                    //calculate the decimal form of the monthly rate and place in a variabl
	                    double dblRatedec = dblMnthlyrate / 100;
	                    double dblOneplusratedec = (1 + dblRatedec);
	                    //create the exponent for the payment calculation and place in variable
	                    double dblExponent = Math.pow(dblOneplusratedec, -intTimemnths);
	                    //calculate mortgage payment and place in a variable
	                    double dblPayment = intPrinciple / ((1 - dblExponent) / dblRatedec);
	                    dblIntPaid = (dblLoanBal * dblRatedec);
	                    dblLoanAndInt = dblLoanBal + dblIntPaid;
	                    dblLoanBal = dblLoanAndInt - dblPayment;
	                    intTotInt = intTotInt + (int)dblIntPaid;
	                    DecimalFormat money = new DecimalFormat("$0,000.00");
	                    txtInfo.append("Payment #" + i
	                            + "\nPayment" + (money.format(dblPayment))
	                            + "\nLoan Balance" + (money.format(dblLoanBal))
	                            + "\nInterest Paid" + (money.format(dblIntPaid))
	                            + "\n" + "\n");
	                }
	                intPrin = intPrinciple;
	                pie.clearSlices(); // reset slices array
	                pie.repaint();
	                pie.addSlice(Green, intPrin);
	                pie.addSlice(Blue, intTotInt);
	                pie.repaint();
	                intTotInt = 0;
	            }
	        } else if (source == btnQuit) {
	            //closing the program
	            System.exit(0);
	        }
	    }
	 
	    class PieSlice {
	 
	        Color color = Color.white;
	        float size = 0;
	 
	        PieSlice(Color pColor, float pSize) {
	            color = pColor;
	            size = pSize;
	        }
	    }
	 
	    class PiePanel extends JPanel {
	 
	        private PieSlice[] slice;
	        private int current = 0;
	        private float totalSize = 0;
	        private Color background;
	 
	        public PiePanel(int sliceCount) {
	            slice = new PieSlice[sliceCount];
	            background = getBackground();
	        }
	 
	        public void addSlice(Color sColor, int sSize) {
	            if (current <= slice.length) {
	                slice[current] = new PieSlice(sColor, sSize);
	                totalSize += sSize;
	                current++;
	            }
	        }
	 
	        public void clearSlices() {
	            current = 0;
	            totalSize =0;
	            for (int i = current; i < slice.length; i++) {
	                slice[i] = null;
	            }
	        }
	 
        @Override
	        public void paintComponent(Graphics comp) {
	            super.paintComponents(comp);
	            Graphics2D comp2D = (Graphics2D) comp;
	            int width = getSize().width - 10;
	            int height = getSize().height - 15;
	            int xInset = 5;
	            int yInset = 5;
	            if (width < 5) {
	                xInset = width;
	            }
	            if (height < 5) {
	                yInset = height;
	            }
	            comp2D.setColor(background);
	            comp2D.fillRect(0, 0, getSize().width, getSize().height);
	            comp2D.setColor(Color.white);
	            Ellipse2D.Float pie = new Ellipse2D.Float(
	                    xInset, yInset, width, height);
	            comp2D.fill(pie);
	            float start = 0;
	            for (int i = 0; i < slice.length; i++) {
	                float extent = slice[i].size * 360F / totalSize;
	                comp2D.setColor(slice[i].color);
	                Arc2D.Float drawSlice = new Arc2D.Float(
	                        xInset, yInset, width, height, start, extent,
	                        Arc2D.Float.PIE);
	                start += extent;
	                comp2D.fill(drawSlice);
	            }
	        }
	    }
	}


The only thing that I see wrong now when I run the application is when I put the amount of 200000 into the box and click calculate, I get errors. Please see if you get the same so I can try and fix.
Was This Post Helpful? 0
  • +
  • -

#9 macosxnerd101  Icon User is online

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12218
  • View blog
  • Posts: 45,291
  • Joined: 27-December 08

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 08:43 PM

What are the errors? Please post them here.
Was This Post Helpful? 0
  • +
  • -

#10 falloncade  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 17-July 11

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 08:53 PM

View Postmacosxnerd101, on 10 September 2011 - 08:43 PM, said:

What are the errors? Please post them here.


I don't get any errors when I compiled the coding. The application appeared correctly, but these are the errors I received when I tried to put the loan amount in and calculate:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at mortgagecalc10.Mortgagecalc10.actionPerformed(Mortgagecalc10.java:128)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6288)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6053)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4651)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4481)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
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:4481)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:643)
at java.awt.EventQueue.access$000(EventQueue.java:84)
at java.awt.EventQueue$1.run(EventQueue.java:602)
at java.awt.EventQueue$1.run(EventQueue.java:600)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:616)
at java.awt.EventQueue$2.run(EventQueue.java:614)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:613)
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
  • +
  • -

#11 macosxnerd101  Icon User is online

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12218
  • View blog
  • Posts: 45,291
  • Joined: 27-December 08

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 09:02 PM

Is anything showing in the JComboBox? Because if strAnswer is null, that would account for a NullPointerException here:
if (strAnswer.equals("7 years at 5.35%")) {


Was This Post Helpful? 0
  • +
  • -

#12 falloncade  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 17-July 11

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 09:12 PM

View Postmacosxnerd101, on 10 September 2011 - 09:02 PM, said:

Is anything showing in the JComboBox? Because if strAnswer is null, that would account for a NullPointerException here:
if (strAnswer.equals("7 years at 5.35%")) {


I'm still learning so you will have to be patient and explain some what what you mean. However, there is nothing showing.
Was This Post Helpful? 0
  • +
  • -

#13 macosxnerd101  Icon User is online

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12218
  • View blog
  • Posts: 45,291
  • Joined: 27-December 08

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 09:14 PM

Since nothing is in the JComboBox, that means the File I/O portion isn't working correctly or there isn't anything in the File. And since you don't get an Exception printed to the console regarding this, I would assume it's the latter.
Was This Post Helpful? 0
  • +
  • -

#14 falloncade  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 17-July 11

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 09:16 PM

View Postmacosxnerd101, on 10 September 2011 - 09:14 PM, said:

Since nothing is in the JComboBox, that means the File I/O portion isn't working correctly or there isn't anything in the File. And since you don't get an Exception printed to the console regarding this, I would assume it's the latter.

Ok. Now I'm lost. What does that mean? Or I probably should ask, what did I do wrong?
Was This Post Helpful? 0
  • +
  • -

#15 macosxnerd101  Icon User is online

  • Games, Graphs, and Auctions
  • member icon




Reputation: 12218
  • View blog
  • Posts: 45,291
  • Joined: 27-December 08

Re: Mortgage calculator request #7 help

Posted 10 September 2011 - 09:20 PM

This is the method that reads the File data into the JComboBox. If the LoanData.txt File wasn't found, you would have gotten a message printed in the console regarding this. See the catch block. Since nothing is being read, or perhaps null is being read, that is what is being added to the JComboBox. What are the contents of this File? And more importantly, why are you reading from a File for this? You have three options you are looking for in the actionPerformed() method. Why not just hard-code those into the JComboBox?
private void getTermsFromFile() {
	       try {//populate the combobox with it's values
	            String strLine;
	 
	            BufferedReader stmTerms = new BufferedReader(new FileReader("LoanData.txt"));
	            for (int a = 0; a <= 2; a++) {
	                strLine = stmTerms.readLine();
	                strTerm[a] = strLine;
	                cmbTerm.addItem(strLine);
	            }
	        } catch (Exception ex) {
	            System.out.println(ex.toString());
	        }
	    }


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2