12 Replies - 7220 Views - Last Post: 20 September 2010 - 07:56 AM Rate Topic: -----

#1 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Displaying Graph in mortgage calculator

Posted 19 September 2010 - 11:37 AM

Hi. Its me again. I have been working on adding a functioning pie chart to my mortgage calculator. I have created a seperate file to create the graph and would like to make it so that when the user clicks "calculate" another frame will open to display the chart. I want to make it so the display chart closes when the user exits the program. I know I will have to add stuff to both of my action listeners, and call the DisplayChart class from my main program. My problem is understanding how to implement my new code into my existing code to make the two files work together.

I am posting my working Mortgage calculator code, the displaychart code, and an example of what I know I need to do to call the display chart but need to incorporate it into my program.

Here is the code to my functioning program:
/*
 
/** Mortgage Calculator Program
 * Week 5 PRG421
 *Change Request #7
High-Level Requirements
Requestor:  Ninfa Pendleton - Rapid City, SD
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:
- 5 years at 5%
- 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 year and 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
(functioning pie chart or bar graph, that shows loan principal, total interest, and total amount paid over loan).
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.



 *
 *Author: 
 *Due September 20, 2010*/
//import needed packages
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;

//declare calculator class
public class Calculator extends JFrame {

    // Double[] rates;

    // Holds years, interest rate strings read from file
    ArrayList<String> standardTerms = new ArrayList<String>();
    String[] rates;
    String[] years;


    private JLabel amountLabel = new JLabel("Mortgage Amount:");
    private JTextField amount = new JTextField();
    private JLabel termLabel = new JLabel("Term of Loan:");
    private JTextField term = new JTextField();
    private JLabel rateLabel = new JLabel("Rate: ('0.0525')");
    private JTextField rate = new JTextField();
    private JComboBox termList = new JComboBox();
    private JLabel payLabel = new JLabel("Monthly Payment:");
    private JLabel payment = new JLabel();
    private JButton calculate = new JButton("Calculate");
    private JButton clear = new JButton("Clear");
    private JButton exit = new JButton("Exit");
    private JTextArea paymentSchedule = new JTextArea();
    private JScrollPane schedulePane = new JScrollPane(paymentSchedule);
    private Container cp = getContentPane();

    public Calculator(String title) {
        super.setTitle(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        getStandardLoanTermsFromFile();



        termList.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox) e.getSource();

                int cbIndex = cb.getSelectedIndex();

                if (cbIndex > -1) {
                    String[] parts = standardTerms.get(cbIndex).split(",");

                    term.setText(years[cbIndex]);
                    rate.setText(rates[cbIndex]);
                }
            }
        });

        //handle the button events
        calculate.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    //calculate the payments.
                    double p = Double.parseDouble(amount.getText());
                    double r = Double.parseDouble(rate.getText()) / 12;
                    double n = Integer.parseInt(term.getText()) * 12;
                    double monthlyPayment = p * Math.pow(1 + r, n) * r / (Math.pow(1 + r, n) - 1);
                    DecimalFormat df = new DecimalFormat("$###,###.00");
                    payment.setText(df.format(monthlyPayment));


                    //calculate the loan information

                    double principal = p;
                    int month;
                    StringBuffer buffer = new StringBuffer();
                    buffer.append("Month\tAmount\tInterest\tBalance\n");
                    for (int i = 0; i < n; i++) {
                        month = i + 1;
                        double interest = principal * r;
                        double balance = principal + interest - monthlyPayment;
                        buffer.append(month + "\t");
                        buffer.append(new String(df.format(principal)) + "\t");
                        buffer.append(new String(df.format(interest)) + "\t");
                        buffer.append(new String(df.format(balance)) + "\n");
                        principal = balance;

                    }
                    paymentSchedule.setText(buffer.toString());
                } catch (Exception ex) {
                    System.out.println(ex);
                }
            }
        });

        clear.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                term.setText("");
                rate.setText("");
                amount.setText("");
                payment.setText("");
                paymentSchedule.setText("");
            }
        });


        exit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(1);
            }
        });

        JPanel calcScreen = new JPanel();
        calcScreen.setLayout(new GridLayout(10, 4));
        calcScreen.add(amountLabel);
        calcScreen.add(amount);
        calcScreen.add(new Label("Select Mortgage Terms from List or enter manually"));
        calcScreen.add(termList);
        calcScreen.add(termLabel);
        calcScreen.add(term);
        calcScreen.add(rateLabel);
        calcScreen.add(rate);
        calcScreen.add(payLabel);
        calcScreen.add(payment);

        JPanel buttons = new JPanel();
        buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
        buttons.add(calculate);
        buttons.add(clear);
        buttons.add(exit);

        JPanel calc = new JPanel();
        calc.setLayout(new BoxLayout(calc, BoxLayout.Y_AXIS));
        calc.add(calcScreen);
        calc.add(buttons);
        cp.add(BorderLayout.NORTH, calc);
        cp.add(BorderLayout.CENTER, schedulePane);

    }
   /** class MyPanel extends JPanel
{
  public void paintComponent( Graphics g )
  {
    super.paintComponent( g ); // Always call the original paintComponent

    // ... before doing your stuff
    Graphics2D g2D = (Graphics2D) g;
            g.setColor(Color.black);
            g.fillRect(0,0,300,400);
            g.setColor(Color.red);
            g.fillRect(40,300,15,15);
            g.setColor(Color.white);
            g.drawString("Total Mortgage Principal  "+ (100 - (int)totalinterestpercentage) + " %",60,312);
            g.drawString("Total Mortgage Interest  "+ (int)totalinterestpercentage + " %",60,337);
            g.setColor(Color.blue);
            g.fillRect(40,325,15,15);
            g.setColor(Color.red);
            g.fillArc(50, 50, 200, 200, 90, 360);
            g.setColor(Color.blue);
            g.fillArc(50, 50, 200, 200, 90, (int) interestdegrees);
            setBackground(Color.black);
  }

}*/

    private void getStandardLoanTermsFromFile() {
        try {
            String line;

            BufferedReader br = new BufferedReader(new FileReader("term.txt"));

            while ((line = br.readLine()) != null) {
                standardTerms.add(line);
                termList.addItem(line);
            }

            br.close();

            int numberOfLoans = standardTerms.size();

            //allocate the arrays

            rates = new String[numberOfLoans];
            years = new String[numberOfLoans];

            String [] temp;

            for (int index = 0; index < numberOfLoans; index ++)
            	{
            		temp = standardTerms.get(index).split(",");

            	years[index] = temp[0];
            	rates[index] = temp[1];
            }

        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }


    public static void main(String[] args) {
        Calculator frame = new Calculator("Mortgage Calculator");
        frame.setSize(400, 600);
        frame.setVisible(true);


    }
}


Here is the code for my displaychart class:
import java.awt.*;
import javax.swing.JPanel;

public class DisplayChart extends JPanel
 {

    public DisplayChart()
    	 {
    	 	JPanel dc = new JPanel();
    	 	add(dc);
		}

    public void paint(Graphics comp)
    {
    	Graphics2D comp2D = (Graphics2D) comp;
    	comp.setColor(Color.gray);
    	comp.fillRect(0,0,300,400);
    	comp.setColor(Color.yellow);
    	comp.fillRect(40,300,15,15);
    	comp.setColor(Color.green);
    	comp.drawString("Total Mortgage Principal " + (100-(int)principal) + "%",60,312);
    	comp.drawString("Total Mortgage Interest " +(int)interest+ "%",60,337);
    	comp.setColor(Color.blue);
    	comp.fillRect(40,325,15,15);
    	comp.setColor(Color.red);
    	comp.fillArc(50,50,200,90,360);
    	comp.setColor(Color.blue);
    	comp.fillArc(50,50,200,200,90, (int)interest + principal);
    	setBackground(Color.black);
    }

}


and I know i have to put something like this in my program somewhere to get it to work:
ublic class Viewer {

    public static void main(String[] args)
    	 {
    	 	JFrame frame = new Jframe();
    	 	frame.setSize(300,400);
    	 	frame.setTitle("Mortgage Chart");
    	 	fram.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    	 	DisplayChart component = new DisplayChart();
    	 	frame.add(component);

    	 	frame.setVisible(true);
    }


}


Any guidance or suggestions will be greatly appreciated. Today and tomorrow then I can work with Java for fun instead of out of desparation...LOL
The file that works with the program is also attached.

Attached File(s)

  • Attached File  term.txt (41bytes)
    Number of downloads: 241


Is This A Good Question/Topic? 0
  • +

Replies To: Displaying Graph in mortgage calculator

#2 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Re: Displaying Graph in mortgage calculator

Posted 19 September 2010 - 02:38 PM

I have been working on trying to just get the graph to display in my mortgage calculator GUI instead of trying to make separate frames. I am getting 4 errors all pointing at line 134 of my new code. If someone could just let me know if I am close to getting it I would be grateful...

errors:

Quote

--------------------Configuration: <Default>--------------------
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:134: illegal start of expression
public void paint(Graphics comp)
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:134: illegal start of expression
public void paint(Graphics comp)
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:134: ';' expected
public void paint(Graphics comp)
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:134: ';' expected
public void paint(Graphics comp)
^
4 errors

Process completed.



newest code:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
// package calculator;

/** Mortgage Calculator Program
 * Week 5 PRG421
 *Change Request #7
High-Level Requirements
Requestor:  Ninfa Pendleton - Rapid City, SD
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:
- 5 years at 5%
- 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 year and 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
(functioning pie chart or bar graph, that shows loan principal, total interest, and total amount paid over loan).
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.



 *
 *Author: Stacey Estey
 *Due September 20, 2010*/
//import needed packages
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;

//declare calculator class
public class Calculator extends JFrame {

    // Double[] rates;

    // Holds years, interest rate strings read from file
    ArrayList<String> standardTerms = new ArrayList<String>();
    String[] rates;
    String[] years;


    private JLabel amountLabel = new JLabel("Mortgage Amount:");
    private JTextField amount = new JTextField();
    private JLabel termLabel = new JLabel("Term of Loan:");
    private JTextField term = new JTextField();
    private JLabel rateLabel = new JLabel("Rate: ('0.0525')");
    private JTextField rate = new JTextField();
    private JComboBox termList = new JComboBox();
    private JLabel payLabel = new JLabel("Monthly Payment:");
    private JLabel payment = new JLabel();
    private JPanel dc = new JPanel(dc);
    private JButton calculate = new JButton("Calculate");
    private JButton clear = new JButton("Clear");
    private JButton exit = new JButton("Exit");
    private JTextArea paymentSchedule = new JTextArea();
    private JScrollPane schedulePane = new JScrollPane(paymentSchedule);
    private Container cp = getContentPane();


    public Calculator(String title) {
        super.setTitle(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        getStandardLoanTermsFromFile();



        termList.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox) e.getSource();

                int cbIndex = cb.getSelectedIndex();

                if (cbIndex > -1) {
                    String[] parts = standardTerms.get(cbIndex).split(",");

                    term.setText(years[cbIndex]);
                    rate.setText(rates[cbIndex]);
                }
            }
        });

        //handle the button events
        calculate.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    //calculate the payments.
                    double p = Double.parseDouble(amount.getText());
                    double r = Double.parseDouble(rate.getText()) / 12;
                    double n = Integer.parseInt(term.getText()) * 12;
                    double monthlyPayment = p * Math.pow(1 + r, n) * r / (Math.pow(1 + r, n) - 1);
                    DecimalFormat df = new DecimalFormat("$###,###.00");
                    payment.setText(df.format(monthlyPayment));


                    //calculate the loan information

                    double principal = p;
                    int month;
                    StringBuffer buffer = new StringBuffer();
                    buffer.append("Month\tAmount\tInterest\tBalance\n");
                    for (int i = 0; i < n; i++) {
                        month = i + 1;
                        double interest = principal * r;
                        double balance = principal + interest - monthlyPayment;
                        buffer.append(month + "\t");
                        buffer.append(new String(df.format(principal)) + "\t");
                        buffer.append(new String(df.format(interest)) + "\t");
                        buffer.append(new String(df.format(balance)) + "\n");
                        principal = balance;

                    }
                    paymentSchedule.setText(buffer.toString());
                } catch (Exception ex) {
                    System.out.println(ex);
                }
            }
        });



  public void paint(Graphics comp)
    {
    	JPanel dc = new JPanel();
    	 	add(dc);

    	Graphics2D comp2D = (Graphics2D) comp;
    	comp.setColor(Color.gray);
    	comp.fillRect(0,0,300,400);
    	comp.setColor(Color.yellow);
    	comp.fillRect(40,300,15,15);
    	comp.setColor(Color.green);
    	comp.drawString("Total Mortgage Principal " + (100-(int)principal) + "%",60,312);
    	comp.drawString("Total Mortgage Interest " +(int)interest+ "%",60,337);
    	comp.setColor(Color.blue);
    	comp.fillRect(40,325,15,15);
    	comp.setColor(Color.red);
    	comp.fillArc(50,50,200,90,360);
    	comp.setColor(Color.blue);
    	comp.fillArc(50,50,200,200,90, (int)interest + principal);
    	setBackground(Color.black);

    }

        clear.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                term.setText("");
                rate.setText("");
                amount.setText("");
                payment.setText("");
                paymentSchedule.setText("");
            }
        });


        exit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(1);
            }
        });

        JPanel calcScreen = new JPanel();
        calcScreen.setLayout(new GridLayout(10, 4));
        calcScreen.add(amountLabel);
        calcScreen.add(amount);
        calcScreen.add(new Label("Select Mortgage Terms from List or enter manually"));
        calcScreen.add(termList);
        calcScreen.add(termLabel);
        calcScreen.add(term);
        calcScreen.add(rateLabel);
        calcScreen.add(rate);
        calcScreen.add(payLabel);
        calcScreen.add(payment);

        JPanel buttons = new JPanel();
        buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
        buttons.add(calculate);
        buttons.add(clear);
        buttons.add(exit);

        JPanel calc = new JPanel();
        calc.setLayout(new BoxLayout(calc, BoxLayout.Y_AXIS));
        calc.add(calcScreen);
        calc.add(buttons);
        cp.add(BorderLayout.NORTH, calc);
        cp.add(BorderLayout.CENTER, schedulePane);

    }


    private void getStandardLoanTermsFromFile() {
        try {
            String line;

            BufferedReader br = new BufferedReader(new FileReader("term.txt"));

            while ((line = br.readLine()) != null) {
                standardTerms.add(line);
                termList.addItem(line);
            }

            br.close();

            int numberOfLoans = standardTerms.size();

            //allocate the arrays

            rates = new String[numberOfLoans];
            years = new String[numberOfLoans];

            String [] temp;

            for (int index = 0; index < numberOfLoans; index ++)
            	{
            		temp = standardTerms.get(index).split(",");

            	years[index] = temp[0];
            	rates[index] = temp[1];
            }

        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }


    public static void main(String[] args) {
        Calculator frame = new Calculator("Mortgage Calculator");
        frame.setSize(400, 600);
        frame.setVisible(true);


    }
}


I have been reading all the other threads on your site tryiong to get it right...help please!!!!!
Was This Post Helpful? 0
  • +
  • -

#3 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10695
  • View blog
  • Posts: 39,790
  • Joined: 27-December 08

Re: Displaying Graph in mortgage calculator

Posted 19 September 2010 - 02:41 PM

It looks like you are overriding paint() inside the constructor. Remember- you cannot declare methods inside otehr methods. You must move it outside of the constructor.
Was This Post Helpful? 0
  • +
  • -

#4 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Re: Displaying Graph in mortgage calculator

Posted 19 September 2010 - 03:00 PM

View Postmacosxnerd101, on 19 September 2010 - 01:41 PM, said:

It looks like you are overriding paint() inside the constructor. Remember- you cannot declare methods inside otehr methods. You must move it outside of the constructor.

Thanks macosxnerd101 I moved the code I have outside of the constructor and now it is not reading my variables. Here are my errors:
--------------------Configuration: <Default>--------------------
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:228: cannot find symbol
symbol : variable principal
location: class Calculator
comp.drawString("Total Mortgage Principal " + (100-(int)principal) + "%",60,312);
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:229: cannot find symbol
symbol : variable interest
location: class Calculator
comp.drawString("Total Mortgage Interest " +(int)interest+ "%",60,337);
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:233: fillArc(int,int,int,int,int,int) in java.awt.Graphics cannot be applied to (int,int,int,int,int)
comp.fillArc(50,50,200,90,360);
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:235: cannot find symbol
symbol : variable interest
location: class Calculator
comp.fillArc(50,50,200,200,90, (int)interest + principal);
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:235: cannot find symbol
symbol : variable principal
location: class Calculator
comp.fillArc(50,50,200,200,90, (int)interest + principal);
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:235: operator + cannot be applied to int,principal

comp.fillArc(50,50,200,200,90, (int)interest + principal);
^
C:\Users\Stacey\Documents\JCreator LE\MyProjects2\Calculator\src\Calculator.java:235: fillArc(int,int,int,int,int,int) in java.awt.Graphics cannot be applied to (int,int,int,int,int,<nulltype>)
comp.fillArc(50,50,200,200,90, (int)interest + principal);
^
7 errors

Process completed.


and here is my latest version of the program..
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
// package calculator;

/** Mortgage Calculator Program
 * Week 5 PRG421
 *Change Request #7
High-Level Requirements
Requestor:  Ninfa Pendleton - Rapid City, SD
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:
- 5 years at 5%
- 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 year and 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
(functioning pie chart or bar graph, that shows loan principal, total interest, and total amount paid over loan).
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.



 *
 *Author: Stacey Estey
 *Due September 20, 2010*/
//import needed packages
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;

//declare calculator class
public class Calculator extends JFrame {

    // Double[] rates;

    // Holds years, interest rate strings read from file
    ArrayList<String> standardTerms = new ArrayList<String>();
    String[] rates;
    String[] years;


    private JLabel amountLabel = new JLabel("Mortgage Amount:");
    private JTextField amount = new JTextField();
    private JLabel termLabel = new JLabel("Term of Loan:");
    private JTextField term = new JTextField();
    private JLabel rateLabel = new JLabel("Rate: ('0.0525')");
    private JTextField rate = new JTextField();
    private JComboBox termList = new JComboBox();
    private JLabel payLabel = new JLabel("Monthly Payment:");
    private JLabel payment = new JLabel();
    private JButton calculate = new JButton("Calculate");
    private JButton clear = new JButton("Clear");
    private JButton exit = new JButton("Exit");
    private JTextArea paymentSchedule = new JTextArea();
    private JScrollPane schedulePane = new JScrollPane(paymentSchedule);
    private Container cp = getContentPane();


    public Calculator(String title) {
        super.setTitle(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        getStandardLoanTermsFromFile();



        termList.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox) e.getSource();

                int cbIndex = cb.getSelectedIndex();

                if (cbIndex > -1) {
                    String[] parts = standardTerms.get(cbIndex).split(",");

                    term.setText(years[cbIndex]);
                    rate.setText(rates[cbIndex]);
                }
            }
        });

        //handle the button events
        calculate.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    //calculate the payments.
                    double p = Double.parseDouble(amount.getText());
                    double r = Double.parseDouble(rate.getText()) / 12;
                    double n = Integer.parseInt(term.getText()) * 12;
                    double monthlyPayment = p * Math.pow(1 + r, n) * r / (Math.pow(1 + r, n) - 1);
                    DecimalFormat df = new DecimalFormat("$###,###.00");
                    payment.setText(df.format(monthlyPayment));


                    //calculate the loan information

                    double principal = p;
                    int month;
                    StringBuffer buffer = new StringBuffer();
                    buffer.append("Month\tAmount\tInterest\tBalance\n");
                    for (int i = 0; i < n; i++) {
                        month = i + 1;
                        double interest = principal * r;
                        double balance = principal + interest - monthlyPayment;
                        buffer.append(month + "\t");
                        buffer.append(new String(df.format(principal)) + "\t");
                        buffer.append(new String(df.format(interest)) + "\t");
                        buffer.append(new String(df.format(balance)) + "\n");
                        principal = balance;

                    }
                    paymentSchedule.setText(buffer.toString());
                } catch (Exception ex) {
                    System.out.println(ex);
                }
            }
        });





        clear.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                term.setText("");
                rate.setText("");
                amount.setText("");
                payment.setText("");
                paymentSchedule.setText("");
            }
        });


        exit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(1);
            }
        });

        JPanel calcScreen = new JPanel();
        calcScreen.setLayout(new GridLayout(10, 4));
        calcScreen.add(amountLabel);
        calcScreen.add(amount);
        calcScreen.add(new Label("Select Mortgage Terms from List or enter manually"));
        calcScreen.add(termList);
        calcScreen.add(termLabel);
        calcScreen.add(term);
        calcScreen.add(rateLabel);
        calcScreen.add(rate);
        calcScreen.add(payLabel);
        calcScreen.add(payment);

        JPanel buttons = new JPanel();
        buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
        buttons.add(calculate);
        buttons.add(clear);
        buttons.add(exit);

        JPanel calc = new JPanel();
        calc.setLayout(new BoxLayout(calc, BoxLayout.Y_AXIS));
        calc.add(calcScreen);
        calc.add(buttons);
        cp.add(BorderLayout.NORTH, calc);
        cp.add(BorderLayout.CENTER, schedulePane);

    }


    private void getStandardLoanTermsFromFile() {
        try {
            String line;

            BufferedReader br = new BufferedReader(new FileReader("term.txt"));

            while ((line = br.readLine()) != null) {
                standardTerms.add(line);
                termList.addItem(line);
            }

            br.close();

            int numberOfLoans = standardTerms.size();

            //allocate the arrays

            rates = new String[numberOfLoans];
            years = new String[numberOfLoans];

            String [] temp;

            for (int index = 0; index < numberOfLoans; index ++)
            	{
            		temp = standardTerms.get(index).split(",");

            	years[index] = temp[0];
            	rates[index] = temp[1];
            }

        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }
     public void paint(Graphics comp)
    {
    	JPanel dc = new JPanel();
    	 	add(dc);

    	Graphics2D comp2D = (Graphics2D) comp;
    	comp.setColor(Color.gray);
    	comp.fillRect(0,0,300,400);
    	comp.setColor(Color.yellow);
    	comp.fillRect(40,300,15,15);
    	comp.setColor(Color.green);
    	comp.drawString("Total Mortgage Principal " + (100-(int)principal) + "%",60,312);
    	comp.drawString("Total Mortgage Interest " +(int)interest+ "%",60,337);
    	comp.setColor(Color.blue);
    	comp.fillRect(40,325,15,15);
    	comp.setColor(Color.red);
    	comp.fillArc(50,50,200,90,360);
    	comp.setColor(Color.blue);
    	comp.fillArc(50,50,200,200,90, (int)interest + principal);
    	setBackground(Color.black);

    }


    public static void main(String[] args) {
        Calculator frame = new Calculator("Mortgage Calculator");
        frame.setSize(400, 600);
        frame.setVisible(true);


    }
}
Thanks for your input. I have to figure this out by tomorrow at midnight.
Was This Post Helpful? 0
  • +
  • -

#5 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10695
  • View blog
  • Posts: 39,790
  • Joined: 27-December 08

Re: Displaying Graph in mortgage calculator

Posted 19 September 2010 - 03:11 PM

Most of these errors are Cannot Find Symbol b/c you declare the variables in a for loop. As such, these variables are local to that loop and cannot be accessed outside of it. The errors about fillArc() are pretty self-explanatory. Check the API for the Graphics and Graphics2D classes to make sure you are invoking the method you want to.
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

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

Reputation: 8342
  • View blog
  • Posts: 31,883
  • Joined: 06-March 08

Re: Displaying Graph in mortgage calculator

Posted 19 September 2010 - 03:59 PM

Please narrow down your problem
Your asking us to read hundred and hundred of lines of code
We are willing to cut & paste your code to test it but where do you really have a problem ?
Was This Post Helpful? 1
  • +
  • -

#7 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Re: Displaying Graph in mortgage calculator

Posted 19 September 2010 - 06:40 PM

View Postpbl, on 19 September 2010 - 02:59 PM, said:

Please narrow down your problem
Your asking us to read hundred and hundred of lines of code
We are willing to cut & paste your code to test it but where do you really have a problem ?

Hi Pbl...Thanks, and sorry I wasn't more clear.

I am working with two files and the lines of code that I know I need to work on in the main class "Calculator" are:

Line 62
Line 173
Line 174
Line 229
Line 230

In the DisplayChart class I am having trouble with:
Line 34
I also have dummy figures in Lines 29, 30, and 36.
If I comment out line 34, my main program will compile and run, but when my GUI displays the partial graphic distorts the rest of the GUI and my text area completely disappears. My graph is supposed to illustrate the total interest(rate * principal), and the total principal paid over life of the loan (principal + totalInterest). I am more worried about getting the graphic to diplay without ruining my GUI than I am the calculations it displays. If I comment out all the lines I listed in the Calculator file you can see my functioning GUI.
Calculator code:
/** Mortgage Calculator Program
 * Week 5 PRG421
 *Change Request #7
High-Level Requirements
Requestor:  Ninfa Pendleton - Rapid City, SD
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:
- 5 years at 5%
- 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 year and 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
(functioning pie chart or bar graph, that shows loan principal, total interest, and total amount paid over loan).
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.



 *
 *Author: Stacey Estey
 *Due September 20, 2010*/

//import needed packages
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;

//declare calculator class
public class Calculator extends JFrame {



    // Holds years, interest rate strings read from file
    ArrayList<String> standardTerms = new ArrayList<String>();
    String[] rates;
    String[] years;


    private JLabel amountLabel = new JLabel("Mortgage Amount:");
    private JTextField amount = new JTextField();
    private JLabel termLabel = new JLabel("Term of Loan:");
    private JTextField term = new JTextField();
    private JLabel rateLabel = new JLabel("Rate: ('0.0525')");
    private JTextField rate = new JTextField();
    private JComboBox termList = new JComboBox();
    private JLabel payLabel = new JLabel("Monthly Payment:");
    private JLabel payment = new JLabel();
    private JButton calculate = new JButton("Calculate");
    private JButton clear = new JButton("Clear");
    private JButton exit = new JButton("Exit");
    private JTextArea paymentSchedule = new JTextArea();
    private JScrollPane schedulePane = new JScrollPane(paymentSchedule);
    private JLabel displayChart = new JLabel("Mortgage Graph");
    private Container cp = getContentPane();


    public Calculator(String title) {
        super.setTitle(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        getStandardLoanTermsFromFile();



        termList.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox) e.getSource();

                int cbIndex = cb.getSelectedIndex();

                if (cbIndex > -1) {
                    String[] parts = standardTerms.get(cbIndex).split(",");

                    term.setText(years[cbIndex]);
                    rate.setText(rates[cbIndex]);
                }
            }
        });

        //handle the button events
        calculate.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    //calculate the payments.
                    double p = Double.parseDouble(amount.getText());
                    double r = Double.parseDouble(rate.getText()) / 12;
                    double n = Integer.parseInt(term.getText()) * 12;
                    double monthlyPayment = p * Math.pow(1 + r, n) * r / (Math.pow(1 + r, n) - 1);
                    DecimalFormat df = new DecimalFormat("$###,###.00");
                    payment.setText(df.format(monthlyPayment));


                    //calculate the loan information

                    double principal = p;
                    int month;
                    StringBuffer buffer = new StringBuffer();
                    buffer.append("Month\tAmount\tInterest\tBalance\n");
                    for (int i = 0; i < n; i++) {
                        month = i + 1;
                        double interest = principal * r;
                        double balance = principal + interest - monthlyPayment;
                        buffer.append(month + "\t");
                        buffer.append(new String(df.format(principal)) + "\t");
                        buffer.append(new String(df.format(interest)) + "\t");
                        buffer.append(new String(df.format(balance)) + "\n");
                        principal = balance;

                    }
                    paymentSchedule.setText(buffer.toString());
                } catch (Exception ex) {
                    System.out.println(ex);
                }
            }
        });





        clear.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                term.setText("");
                rate.setText("");
                amount.setText("");
                payment.setText("");
                paymentSchedule.setText("");
            }
        });


        exit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.exit(1);
            }
        });

        JPanel calcScreen = new JPanel();
        calcScreen.setLayout(new GridLayout(10, 4));
        calcScreen.add(amountLabel);
        calcScreen.add(amount);
        calcScreen.add(new Label("Select Mortgage Terms from List or enter manually"));
        calcScreen.add(termList);
        calcScreen.add(termLabel);
        calcScreen.add(term);
        calcScreen.add(rateLabel);
        calcScreen.add(rate);
        calcScreen.add(payLabel);
        calcScreen.add(payment);




        JPanel buttons = new JPanel();
        buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
        buttons.add(calculate);
        buttons.add(clear);
        buttons.add(exit);

      JPanel component = new JPanel();
       add(component);



        JPanel calc = new JPanel();
        calc.setLayout(new BoxLayout(calc, BoxLayout.Y_AXIS));
        calc.add(calcScreen);
        calc.add(buttons);
        cp.add(BorderLayout.NORTH, calc);
        cp.add(BorderLayout.CENTER, schedulePane);
        cp.add(BorderLayout.SOUTH, displayChart);

    }


    private void getStandardLoanTermsFromFile() {
        try {
            String line;

            BufferedReader br = new BufferedReader(new FileReader("term.txt"));

            while ((line = br.readLine()) != null) {
                standardTerms.add(line);
                termList.addItem(line);
            }

            br.close();

            int numberOfLoans = standardTerms.size();

            //allocate the arrays

            rates = new String[numberOfLoans];
            years = new String[numberOfLoans];

            String [] temp;

            for (int index = 0; index < numberOfLoans; index ++)
            	{
            		temp = standardTerms.get(index).split(",");

            	years[index] = temp[0];
            	rates[index] = temp[1];
            }

        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }



    public static void main(String[] args) {
        Calculator frame = new Calculator("Mortgage Calculator");
        frame.setSize(800, 900);
       DisplayChart component = new DisplayChart();
    	 	frame.add(component);


        frame.setVisible(true);


    }
}


DisplayChart Class:
/**
 * @(#)Text1.java
 *
 *
 * @author
 * @version 1.00 2010/9/19
 */
import java.awt.*;
import javax.swing.JPanel;

public class DisplayChart extends JPanel
 {

    public DisplayChart()
    	 {
    	 	JPanel dc = new JPanel();
    	 	add(dc);
		}

    public void paint(Graphics comp)
    {

    	Graphics2D comp2D = (Graphics2D) comp;
    	comp.setColor(Color.magenta);
    	comp.fillRect(0,0,300,400);
    	comp.setColor(Color.yellow);
    	comp.fillRect(40,300,15,15);
    	comp.setColor(Color.green);
    	comp.drawString("Total Mortgage Principal " + (100-(int)20000),60,312);
    	comp.drawString("Total Mortgage Interest " +(int)50 + "%",60,337);
    	comp.setColor(Color.blue);
    	comp.fillRect(40,325,15,15);
    	comp.setColor(Color.red);
    	comp.fillArc(50,50,200,90,360);
    	comp.setColor(Color.blue);
    	comp.fillArc(50,50,200,200,90, (int)180  );
    	setBackground(Color.black);
    }

}


Thank you for taking the time to help me I really appreciate it.
The text file my program reads is also attached.

Attached File(s)

  • Attached File  term.txt (41bytes)
    Number of downloads: 220

Was This Post Helpful? 0
  • +
  • -

#8 n8wxs  Icon User is offline

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

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

Re: Displaying Graph in mortgage calculator

Posted 19 September 2010 - 07:01 PM

You can pass the principal and interest to DisplayChart if you use a constructor that takes the two arguments and stores them as instance variables. That way you don't hardcode the values in the drawString() calls.
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

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

Reputation: 8342
  • View blog
  • Posts: 31,883
  • Joined: 06-March 08

Re: Displaying Graph in mortgage calculator

Posted 19 September 2010 - 07:31 PM

View Postn8wxs, on 19 September 2010 - 08:01 PM, said:

You can pass the principal and interest to DisplayChart if you use a constructor that takes the two arguments and stores them as instance variables. That way you don't hardcode the values in the drawString() calls.

I am always astonished as n8wxs has always simple solutions for any problem
I guess 80 years of experience explain it :)
Was This Post Helpful? 0
  • +
  • -

#10 n8wxs  Icon User is offline

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

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

Re: Displaying Graph in mortgage calculator

Posted 19 September 2010 - 08:07 PM

I ain't a geezer yet!!!!!!!!!!!!!!!!


:wheelchair:
Was This Post Helpful? 0
  • +
  • -

#11 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10695
  • View blog
  • Posts: 39,790
  • Joined: 27-December 08

Re: Displaying Graph in mortgage calculator

Posted 19 September 2010 - 09:20 PM

View Postn8wxs, on 19 September 2010 - 11:07 PM, said:

I ain't a geezer manager yet!!!!!!!!!!!!!!!!


:wheelchair:

But with the simplicity and accuracy of your answers, you would make a damn good one, imho, by getting things done. :)
Was This Post Helpful? 0
  • +
  • -

#12 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Re: Displaying Graph in mortgage calculator

Posted 20 September 2010 - 05:24 AM

View Postn8wxs, on 19 September 2010 - 06:01 PM, said:

You can pass the principal and interest to DisplayChart if you use a constructor that takes the two arguments and stores them as instance variables. That way you don't hardcode the values in the drawString() calls.

Okay, thank you. But my major problem is getting it to display right in my GUI. When I run the program with line 34 of the DisplayChart class commented out the GUI is all distorted...it makes my textfields and buttons duplicate, and my text area where the loan information appears is gone, and the Graphic is right on top of it all. With your suggestions above I can handle getting the calculations worked out but I need to get my GUI to display properly. Thank you and Pbl both for your help. Today is my last day of JavaII, I have till midnight. If I can at least get my graphic to display right, then I can handle the calculations and pass this class. =)
Was This Post Helpful? 0
  • +
  • -

#13 MrsE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 35
  • Joined: 06-September 10

Re: Displaying Graph in mortgage calculator

Posted 20 September 2010 - 07:56 AM

View Postpbl, on 19 September 2010 - 02:59 PM, said:

Please narrow down your problem
Your asking us to read hundred and hundred of lines of code
We are willing to cut & paste your code to test it but where do you really have a problem ?

Hi Pbl I listed the lines of code I need help with in post #7 can you give me any pointers on how I should change anything so my GUI format displays correctly? I am trying to make the graph appear below the text area that displays the loan details. Thank you for your time.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1