Link to home
Start Free TrialLog in
Avatar of ghost8067
ghost8067

asked on

Create a chart from calculated values in a mortgage calculator

Hi,
My program pasted below caslculates a mortgage payment and displays an amortization table. I have also added the basic axis lines to a graph at the bottom. I have 2 questions. My graph displays the X axis at the top of the graph. I would like to move that to the bottom so it looks like an "L" I then want to display a line that graphs the principle paid along the x axis and the interest paid along the y axis.These values are already calculated in my display button event.
Any help or clues would be appreciated.
Thanks,
Jon

My code is below:


//week3 Jan Schab


/* Mortgage Monyhly Payment Calculator with graphical user interface
Programmer:  J.Schab
Date:        June 10,2006
Filename:    Mortgage.java
Purpose:     This project accepts the mortgage and allows  the user to select one of 3
pre-determined loans.The program then calculates the monthly mortgage payment and displays
it in currency format. The program then allows the user to display the payment number,
the monthly principle paid, the monthly interest paid, and the current loan balance
through the push of an addition button; There is a quit button to exit the application,
and a clear button to clear user entered fields as well as the amortization table.in
order to calculate a new mortgage. The program will also clear the payment field should
the user press any key while positioned in the input textfield for amount. The payment and
amortizatin table will also be cleared if the user changes the radio buttons.


 */



import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JScrollPane.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.text.NumberFormat;
import java.util.Locale;
import java.text.*;
import java.text.DecimalFormat;
import java.io.FileReader;
import java.io.BufferedReader;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.awt.Dimension;
import java.awt.geom.Line2D;
import java.awt.Graphics2D;
import java.awt.geom.*;






class Mortgage extends JFrame implements ActionListener
{


    //Program variables





    int payment = 0; // payment counter
    int i = 0; // used as index
    // initialize variable for monthly interest rate
    double monthlyInterest = 0.00;
    // variable to store principle
    double principle = 0.00;
    // initialize mothly principle paid field
    double monthlyPrinciplePaid = 0.00;
    // Variable to hold maonthly interest
    double interestRateMonthly = 0.00;
    // variable to store calculated monthly payment
    double monthlyPayment = 0.00;
    // variable to store descending balance
    double monthCount = 0.00;
      double loanbalance = 0.00;
      double calcValue = 0.00;

    int amount = 0;
    String YearlyInterestArrayNew[] = null;

      String TermArrayNew[] = null;

      //String InputFile = "C:\TermRate.dat";





    private JLabel headerJLabel;

    Border rowborder = new EmptyBorder(3, 10, 3, 10);
    // Format output
    DecimalFormat currency = new DecimalFormat("$0.00");


    // JLabel and JTextField for the mortgage amount
    private JLabel amountJLabel;
    private JTextField amountJTextField;

    // JLabel for monthly mortgage payment
    private JLabel monthpayJLabel;

    // JTextArea for displaying payment
    private JTextArea outputJTextArea;


    // JButton to initiate calculations
    private JButton calculateJButton;

    // JButton to display amortization table
    private JButton displayJButton;

    // JButton to clear entries
    private JButton clearJButton;

    // JButton to quit
    private JButton quitJButton;


    // Create radio panel
    JPanel radioPanel = new JPanel();
    JRadioButton aButton = new JRadioButton("7 Years at 5.35%", true);
    JRadioButton bButton = new JRadioButton("15 Years at 5.50%", false);
    JRadioButton cButton = new JRadioButton("30 Years at 5.75%", false);


    // create scroll box with display area
    JTextArea displayArea = new JTextArea(10, 45);
    JScrollPane scroll = new JScrollPane(displayArea);

    ChartPanel  chart = new ChartPanel(  );






    // no-argument constructor
    public Mortgage()



    {
        createUserInterface();
    }

    // create and position the GUI components; register event handlers
    private void createUserInterface()
    {
        // get content pane for attaching GUI components
        Container contentPane = getContentPane();

        setTitle("Mortgage Calculator"); // set title bar text


        // set northLabel using borderlayout
        headerJLabel = new JLabel();
        headerJLabel.setBounds(10, 1, 300, 46); // set size and position
        headerJLabel.setText("Enter a mortgage amount and select a loan");
        contentPane.add(headerJLabel);

        // enable specific positioning of GUI components
        contentPane.setLayout(null);

        // set up amountJLabel
        amountJLabel = new JLabel();
        amountJLabel.setBounds(76, 36, 104, 26); // set size and position
        amountJLabel.setText("Mortgage amount:");
        contentPane.add(amountJLabel);

        // set up amountJTextField
        amountJTextField = new JTextField();
        amountJTextField.setBounds(200, 36, 56, 26); // set size and position
        amountJTextField.setHorizontalAlignment(JTextField.RIGHT);
        contentPane.add(amountJTextField);
        amountJTextField.addKeyListener(

        new KeyAdapter() // anonymous inner class
        {
            // event handler for key pressed in amountJTextField
            public void keyPressed(KeyEvent event)
            {
                amountJTextFieldkeyPressed(event);
            }

        } // end anonymous inner class

        ); // end call to addKeyListener



        // create radio buttons and panel
        ButtonGroup bgroup = new ButtonGroup();
        // add listeners for radio buttons
        aButton.addActionListener(this);
        bButton.addActionListener(this);
        cButton.addActionListener(this);
        bgroup.add(aButton);
        bgroup.add(bButton);
        bgroup.add(cButton);
        radioPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4));
        radioPanel.add(aButton);
        radioPanel.add(bButton);
        radioPanel.add(cButton);
        contentPane.add(radioPanel);
        radioPanel.setBorder(rowborder);
        radioPanel.setBounds(90, 56, 195, 95); // set size and position



        // set up calculateJButton
        calculateJButton = new JButton();
        calculateJButton.setBounds(26, 155, 90, 26); // set size and position
        calculateJButton.setText("Calculate");
        contentPane.add(calculateJButton);
        calculateJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when calculateJButton is pressed
            public void actionPerformed(ActionEvent event)
            {

                calculateJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up displayJButton
        displayJButton = new JButton();
        displayJButton.setBounds(26, 216, 200, 26); // set size and position
        displayJButton.setText("Display Amortization Table");
        contentPane.add(displayJButton);
        displayJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when clearJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                displayJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener




        // set up clearJButton
        clearJButton = new JButton();
        clearJButton.setBounds(70, 380, 90, 26); // set size and position
        clearJButton.setText("Clear");
        contentPane.add(clearJButton);
        clearJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when clearJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                clearJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up quitJButton
        quitJButton = new JButton();
        quitJButton.setBounds(230, 380, 90, 26); // set size and position
        quitJButton.setText("Quit");
        contentPane.add(quitJButton);
        quitJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when quitJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                quitJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up outputJTextArea
        outputJTextArea = new JTextArea();
        contentPane.add(outputJTextArea);
        outputJTextArea.setBounds(300, 155, 56, 26); // set size and position
        outputJTextArea.setEditable(false);

        //set up monthpayJLabel
        monthpayJLabel = new JLabel();
        monthpayJLabel.setBounds(176, 155, 156, 26); // set size and position
        monthpayJLabel.setText("Monthly Payment:");
        contentPane.add(monthpayJLabel);

        scroll.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        contentPane.add(scroll);
        scroll.setBounds(20, 240, 369, 130); // set size and position
        setVisible(true);
        displayArea.setEditable(false);
        contentPane.add(scroll);



            //chart.setMinimumSize(new Dimension( 200, 200 ) );
            //chart.setMaximumSize(new Dimension( 200, 200 ) );
            //chart.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            chart.setBounds(20, 350, 389, 330); // set size and position
            contentPane.add( chart );
            setVisible(true);



FileReader InputFile;
          try {
               InputFile = new FileReader("TermRate.dat");
               BufferedReader data = new BufferedReader(InputFile);
               String aline = null;
               java.util.ArrayList array = new java.util.ArrayList();
               while ((aline = data.readLine()) != null)
                    array.add(aline);
               //      ArrayList YearlyInterestArrayNew = new ArrayList();
                        //           ArrayList TermArrayNew = new ArrayList();

               YearlyInterestArrayNew = new String[array.size()];
               TermArrayNew = new String[array.size()];
               for (int i = 0; i < array.size(); i++) {
                    String[] line = ((String) array.get(i)).split(",");

                    TermArrayNew[i] = line[0].trim();
                    YearlyInterestArrayNew[i] = line[1].trim();
                    //YearlyInterestArrayNew[i] = line[0].trim();
                              //TermArrayNew[i] = line[1].trim();

                    //Integer.parseInt(TermArrayNew[i]);
                              //Integer.parseInt(YearlyInterestArrayNew[i]);



               }

               InputFile.close();
          } catch (Exception e1) {
               e1.printStackTrace();
          }

          //MyComboBox();
     //}


            //double Term = Double.parseDouble((String)TermArrayNew.get(i));
            //double Interest = Double.parseDouble((String)YearlyInterestArrayNew.get(i));






    } // end method createUserInterface

    // called when user presses key in amountJTextField
    private void amountJTextFieldkeyPressed(KeyEvent event)
    {
        outputJTextArea.setText(""); // clear outputJTextArea
        displayArea.setText(""); // clear display
        payment = 0; // reset payment counter
        double monthCount = 0.00;
        double loanbalance = 0.00;

    }

    // method called when user clicks calculateJButton
    private void calculateJButtonActionPerformed(ActionEvent event)
    {
        try
        {
            // check which radio buttonis selected and set index
            if (aButton.isSelected())
            {
                i = 0;
            }


            if (bButton.isSelected())
            {
                i = 1;
            }


            if (cButton.isSelected())
            {
                i = 2;
            }





            //define display area titles
            String titles = "Month \t Principal\t Interest\tBalance\n";
            //put titles in display area
            displayArea.setText(titles);
            // initialize loan balance field


            // initialize payment counter

            // clear outputJTextArea
            outputJTextArea.setText("");
            // clear display area
            displayArea.setText("");
            // Calculate months from years
            //Integer.parseInt(TermArrayNew[i]);
                  //Integer.parseInt(YearlyInterestArrayNew[i]);

             //int monthCount = (term[i] * 12);
            //int monthCount = (term[i] * 12);
            //int monthCount = Integer.parseInt(TermArrayNew[i])* 12;
            double monthCount = Double.parseDouble(TermArrayNew[i])* 12.0;
            //int monthCount = (TermArrayNew[i] * 12);
            // get mortgage amount
            amount = Integer.parseInt(amountJTextField.getText());
            //create variable to store decreasing principle
            principle = amount;
            // Calculate monthly interest

            calcValue = Double.parseDouble(YearlyInterestArrayNew[i]);


            interestRateMonthly = (calcValue / 12.0) / 100.0;
           //interestRateMonthly = Double.parseDouble(YearlyInterestArrayNew[i] / 12) / 100;
            //interestRateMonthly = (Interest / 12) / 100;

            // Calculate monthly payment
            //monthlyPayment = (amount * interestRateMonthly) / (1-Math.pow(1
            //    +interestRateMonthly,  - monthCount));

            monthlyPayment = (amount * interestRateMonthly) / (1-Math.pow(1
                  +interestRateMonthly,  - monthCount));




             //displayArea.append(currency.format(TermArrayNew[0]));


            // Output payment amount
            outputJTextArea.setText(currency.format(monthlyPayment));

            //displayArea.append(currency.format(amount));
            //displayArea.append(currency.format(interestRateMonthly));
           //displayArea.append(currency.format(interestRateMonthly));



        }

        //catch (NumberFormatException ex){}
         catch (NumberFormatException ex)
                   {
                       ex.printStackTrace() ;
                   }

}




    // method called when user clicks clearJButton
    private void clearJButtonActionPerformed(ActionEvent event)
    {
        try
        {

            monthlyPrinciplePaid = 0.00; // initialize principle paid field
            outputJTextArea.setText(""); // clear outputJTextArea
            amountJTextField.setText(""); // clear amountJTextField
            displayArea.setText(""); // clear display area
            payment = 0; // reset payment counter




        }
        catch (NumberFormatException ex){}
    }


    // method called when user clicks displayJButton
    private void displayJButtonActionPerformed(ActionEvent event)
    {
        try
        {

            // reset values in case user presses display more than once
            principle = Integer.parseInt(amountJTextField.getText());
            monthlyPrinciplePaid = 0.00;
            displayArea.setText(""); // clear display
            payment = 0;
            monthlyPrinciplePaid = 0.00;
            double monthCount = Double.parseDouble(TermArrayNew[i])* 12.0;
            calcValue = Double.parseDouble(YearlyInterestArrayNew[i]);


                  interestRateMonthly = (calcValue / 12.0) / 100.0;



            //define display area titles
            String titles = "Month \t Principal\t Interest\tBalance\n";
            //put titles in display area
            displayArea.setText(titles);
            // initialize loan balance field

             Double.parseDouble(TermArrayNew[i]);

            // loop for creating amortization table
            //for (int a = 0; a < TermArrayNew[i]; a = a + 1)
            //for (int a = 0; a < Double.parseDouble(TermArrayNew[i]); a = a + 1)
            for (int a = 0; a < monthCount; a = a + 1)

                        {
                //increment payment counter
                payment++;
                // calculate monthly interest
                monthlyInterest = principle * interestRateMonthly;
                // calculate monthly principle
                monthlyPrinciplePaid = monthlyPayment - monthlyInterest;
                //save declining balance
                principle = principle - monthlyPrinciplePaid;

                //displayArea.append(currency.format(TermArrayNew[0]));
                // display amortization table
                displayArea.append(payment + "\t" + currency.format
                    (monthlyPrinciplePaid) + "\t" + currency.format
                    (monthlyInterest) + "\t" + currency.format(Math.abs
                    (principle)) + "\n");
                displayArea.setCaretPosition(0);


            }
        }

        catch (NumberFormatException ex){}
    }




    // method called when user clicks quitJButton
    private void quitJButtonActionPerformed(ActionEvent event)
    {
        try
        {
            System.exit(0);

        }
        catch (NumberFormatException ex){}
    }

    // method called when user clicks on a radio button
    public void actionPerformed(ActionEvent e)
    {
        displayArea.setText(""); // clear display
        outputJTextArea.setText(""); // clear outputJTextArea



    }

    class ChartPanel extends JPanel
          {
      //      displays graphics chart for payment schedule
              public void paintComponent( Graphics comp )
              {
                  super.paintComponent( comp );

                  Graphics2D  comp2D = (Graphics2D)comp;
                  BasicStroke pen = new BasicStroke( 1F );
                  comp2D.setStroke( pen );

                  //double xStart  = 80F;
                  //double xEnd    = 200F;
                  //double yStart  = 80F;
                  //double yEnd    = 200F;
                  //double xLegend = 65F;


                  double xStart  = 80F;
                  double xEnd    = 240F;
                  double yStart  = 80F;
                  double yEnd    = 240F;
                  double xLegend = 65F;


                  comp2D.setColor( Color.blue );

                  Line2D vLn = new Line2D.Float( (float)xStart, (float)yStart, (float)xStart, (float)yEnd );
                  comp2D.draw( vLn );


                  Line2D hLn = new Line2D.Float( (float)xStart, (float)yStart, (float)xEnd, (float)yStart );
                  comp2D.draw( hLn );


                  Font chartFont = new Font( "Dialog", Font.BOLD, 10 );
                  comp2D.setFont( chartFont );
                  comp2D.setColor( Color.red );
                  comp2D.drawString( "0.00", (float)( xStart - xLegend ), (float)yStart );

                           //double xStep = monthCount / (xEnd - xStart);
                           //double yStep = maxPaymentValue / (yEnd = yStart);
              }
            }

    // main method
    public static void main(String[]args)
    {
        Mortgage application = new Mortgage();
        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        application.setSize(400, 650);
        application.setVisible(true);
    } // end method main

} // end class Mortgage

Avatar of ghost8067
ghost8067

ASKER

I forgot to supply the values in the file the program reads. It is below.

File
7,5.35
15,5.5
30,5.75


Jon
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Canb you porovide any direction as far as plotting the points?
Personally i would'nt implement that myself. I would integrate it with an existing API like JFreeChart.

If you are going to do it yourself, you'll need a larger area to plot the points in if you want to avoid approximation
Unfortunately this is an assignment and I don't have that option. I have been wrestling with it for a few days. I am thinking of plotting the points in the loop where I display the amortization table so the values are available. Does that sound reasonable to you? For each payment that is printed, a point would be generated. It would then function within the same loop. I am accepting the answer because you did solve my first issue. If you could provide any help as to a  to plotting the values it would be appreciated.
Thanks,
Jon
If you're determined to do it yourself, you just need to draw lines, like you did with your axes, between the points. I would give yourself a larger area in which to draw
:-)