Help needed with a pie chart

Not sure how to pass variables

Page 1 of 1

1 Replies - 2869 Views - Last Post: 09 January 2011 - 02:06 PM Rate Topic: -----

#1 midhir   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 27-October 10

Help needed with a pie chart

Posted 09 January 2011 - 01:27 PM

My assignment like others in the past form UoP is to create a pie chart from the calculations from the mortage calculator. I have read though evey other post concerning this program but to no aval. I finally have a generic graph popping up in a new JFrame window, so my question would be how can I pass variables from my buildInterface class to the PieChart2 class?

buildInterface code:

import javaprogramming421.PieChart2;
import java.text.*;                 // Used for currency display
import java.awt.*;                  // Used for graphical chart
import java.awt.event.*;            // Also used for events
import javax.swing.*;               // Used for Graphical Displays
import*;                   // Used for file input and output functions

// The main class for the program
public class buildInterface extends JFrame {

    // Intialize Global Variables
    double loanAmount, inputInterestRate, interestRate, monthlyPayment, totalPaid,
            totalInterestPaid, newLoanAmount, interestPaid, totalLoanAmount, principlePaid;
    int totalYears, totalMonths, paymentNumber, lineCount;
    int [] definedTotalYears = {7,15,30};                    // Array for Term of the loan in years
    String readLine;
    String [] readInterestRates = new String[3];

    NumberFormat money = NumberFormat.getCurrencyInstance(); //Converts numbers to money values

    // Initalize Labels, Text Fields and Buttons Variables
    JLabel loanAmountLbl, interestRateLbl, monthlyPaymentLbl, totalYearsLbl,
           totalPaidLbl, seperateLine, seperateLine2, blankLine, blankLine2, 
           viewPaymentsLbl, predefinedLoanDataLbl, totalInterestPaidLbl,
           textWindowLbl, paymentsHeader, seperateLine3;
    JTextField loanAmountTF, totalMonthsTF, interestRateTF, monthlyPaymentTF,
               totalYearsTF, totalPaidFT, viewPaymentsTF, totalInterestPaidTF;
    JButton calculateButton, clearButton, exitButton, viewPaymentsButton, 
            continueButton, selectButton;
    JRadioButton predefined1, predefined2, predefined3;
    JPanel mainPanel;
    JTextArea myOutputArea;
    JScrollPane myScrollBar;

    public buildInterface() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Close cleanly when X is pressed.

        // Setup the Labels to be used within the window
        loanAmountLbl = new JLabel("Amount of the Loan: $");
        totalYearsLbl = new JLabel("Length of Loan in Years: ");
        interestRateLbl = new JLabel("Interest Rate Percentage: ");
        monthlyPaymentLbl = new JLabel("The Total Monthly Payment Is: ");
        totalInterestPaidLbl = new JLabel("Total Interest Paid: ");
        totalPaidLbl = new JLabel("Final Loan amount ");
        viewPaymentsLbl = new JLabel("View Monthly Payment Schedule");
        seperateLine = new JLabel  ("___________________________________________");
        seperateLine2 = new JLabel  ("___________________________________________");
        seperateLine3 = new JLabel  ("___________________________________________");
        blankLine = new JLabel ("                                                                             ");
        blankLine2 = new JLabel("                                          ");
        predefinedLoanDataLbl = new JLabel("Select Predefined Interest Rates and Terms from Below");
        textWindowLbl = new JLabel("View Payment Information Below");
        paymentsHeader = new JLabel("   Payment #     Remaining Balance     Interest Paid         ");

        //Declare the text fields. The (#) field defines the field size in characters
        loanAmountTF = new JTextField(10);
        totalMonthsTF = new JTextField(4);
        interestRateTF = new JTextField(5);
        monthlyPaymentTF = new JTextField(8);
        totalInterestPaidTF = new JTextField(10);
        totalYearsTF = new JTextField(2);
        totalPaidFT = new JTextField(10);
        // Define buttons with Titles to be used.
        calculateButton = new JButton("Calculate");
        clearButton = new JButton("Clear");
        exitButton = new JButton("Exit");
        selectButton = new JButton("Select Predefined Values");
        viewPaymentsButton = new JButton("Payment Schedule");

        // Define and Initialize Radio Buttons
        predefined1 = new JRadioButton("07 Year Loan, 5.35% Interest");
        predefined2 = new JRadioButton("15 Year Loan, 5.50% Interest");
        predefined3 = new JRadioButton("30 Year Loan, 5.75% Interest" );
        final ButtonGroup radioGroup = new ButtonGroup(); //Groups buttons together
        //Add radio buttons to the group

        //Define and setup text area for system output
        myOutputArea = new JTextArea("",8,27);
        //Create Text Area with a Scroll Bar
        myScrollBar = new JScrollPane(myOutputArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

        // Building the window and adding the buttons, fields and labels.
        mainPanel = new JPanel();                // Create the panel for the window
        setSize(330, 650);                       // Set the size of the window
        setResizable(false);                     // Keeps users from resizing the window (retains layout)
        setLocation(750, 100);                   // Define the location on the screen the app starts at.
        setTitle("McBride Mortgage Calculator"); // Sets the Title of the window

        // Add content to the window
        mainPanel.add(loanAmountLbl);            // Text of the Amount of loan input
        mainPanel.add(loanAmountTF);             // The amount field
        mainPanel.add(totalYearsLbl);            // Text for the Years of loan input
        mainPanel.add(totalYearsTF);             // The total years field
        mainPanel.add(interestRateLbl);          // Text for the interest rate input
        mainPanel.add(interestRateTF);           // The interest rate field
        mainPanel.add(monthlyPaymentLbl);        // Text for the monthly payment output
        mainPanel.add(monthlyPaymentTF);         // Monthly payment field
        monthlyPaymentTF.setEditable(false);     // Prevents users from editing the field
        mainPanel.add(totalInterestPaidLbl);     // Text for Total Interest Paid Field
        mainPanel.add(totalInterestPaidTF);      // Total Interest Paid text field
        totalInterestPaidTF.setEditable(false);  // Make field uneditable
        mainPanel.add(totalPaidLbl);             // Label of Total Paid on Loan
        mainPanel.add(totalPaidFT);              // Text Field for the total loan cost.
        totalPaidFT.setEditable(false);          // Prevents users from editing ther field
        mainPanel.add(blankLine);                // Add a line between the textField and Buttons areas
        mainPanel.add(calculateButton);          // Adds the Calculate button
        mainPanel.add(clearButton);              // Adds the clear fields button
        mainPanel.add(exitButton);               // Adds the exit button
        mainPanel.add(seperateLine);             // Adds a seperation line (temporary)
        mainPanel.add(predefinedLoanDataLbl);    // Adds a text label above the radio buttons
        mainPanel.add(predefined1);              // Displays the RadioButton for  7 year load data
        mainPanel.add(predefined2);              // Displays the RadioButton for 15 year load data
        mainPanel.add(predefined3);              // Displays the RadioButton for 30 year load data
        mainPanel.add(selectButton);             // Button to view loan payment schedual
        mainPanel.add(seperateLine2);            // Add another speration line
        mainPanel.add(viewPaymentsLbl);          // Text for the View Payments option
        mainPanel.add(viewPaymentsButton);       // Add the view payments button
        mainPanel.add(paymentsHeader);           // Text for the text output area
        mainPanel.add(myScrollBar);              // Add the text area with a scroll bar

        //Graph needs to show up here

        mainPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED)); //Nifty border
        add(mainPanel);                          // Create the actual Window
        setVisible(true);                        // Allows window to be seen

        // Initalize Listeners for Buttons
        exitButton.addActionListener(new exitListener());
        clearButton.addActionListener(new clearListener());
        calculateButton.addActionListener(new calculateListener());
        selectButton.addActionListener(new selectListener());
        viewPaymentsButton.addActionListener(new viewPaymentsListener()); 

    } // End buildInterface Contructor

    //Creates a new Data File and write interest rates into it.
    public class FileWrite {
        BufferedWriter fileOut;
        public FileWrite(){
            try {
                    fileOut = new BufferedWriter(new FileWriter("interestRates.txt"));
                    fileOut.newLine();          //Starts a new line
                    fileOut.write("5.35");      //Write out interestRate 1 to the file
                    fileOut.newLine();          //Starts a new line
                    fileOut.write("5.5");       //Write out interestRate 2 to the file
                    fileOut.newLine();          //Starts a new line
                    fileOut.write("5.75");      //Write out interestRate 3 to the file
                    fileOut.newLine();          //Starts a new line
                    fileOut.close();            //flushes and closes the stream
                 } // End Write Out
            catch(IOException e){
                    JOptionPane.showMessageDialog(null, "Error Writing to File" + e);
                } // End Error Catching
            }// End Method
        }// End Class
    FileWrite File = new FileWrite(); // Create the Acuall File
/********************* Begin Current Button Actions ***************************/

    // ActionListener for the Exit Button being pressed. Exits the Program
    public class exitListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == exitButton) {
            } // End if exitButton was Pressed
        } //End Method
    } // End Class

    // ActionListener for the Clear Button Clear text fields and reset variables
    public class clearListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == clearButton) {
            } // End if clearButton was Pressed. All Text Fields are Cleared
        } // End Method
    } // End Class

    //Action Listeners for the select button and radio selections
    public class selectListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == selectButton) {
                // Read the Data file interestRates.txt and load the values into
                //the readInterestRates Array
                try {
                    File dataFile = new File("interestRates.txt");
                    BufferedReader in = new BufferedReader(new FileReader(dataFile));
                    while ((readLine = in.readLine()) != null) {
                        for (int i = 0; i < readInterestRates.length; i++){
                            readInterestRates[i] = in.readLine();
                catch(IOException erf){
                    JOptionPane.showMessageDialog(null, "Error Reading File" + erf);
                    String loan1TY = Integer.toString(definedTotalYears [0]);
                    interestRateTF.setText(readInterestRates [0]);
                    String loan2TY = Integer.toString(definedTotalYears [1]);
                    interestRateTF.setText(readInterestRates [1]);
                    String loan3TY = Integer.toString(definedTotalYears [2]);
                    interestRateTF.setText(readInterestRates [2]);
            } // End if selectButton was Pressed
        } //End Method
    } // End Class

  //ActionListener for the Calculate Button being pressed. Gets Data and Calculates Monthly Payment
    public class calculateListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == calculateButton) {
                /*** Get input for the Loan Amount ***/
                try {
                    // Get string loan amount and covert it into a number
                    loanAmount = Double.parseDouble(loanAmountTF.getText());
                    } //Verify Loan Amount input is numeric
                catch (NumberFormatException n) {
                    JOptionPane.showMessageDialog(null, "Invalid number... Please Re-Enter Loan Amount");
                //Verify Loan amount is not 0
                if (loanAmount < 1) {
                    JOptionPane.showMessageDialog(null, "Invalid Input... Loan Amount must be greater than 0!"
                                                      + "\n Please Do Not include Comas or Dollar signs");

                /*** Get input for the length of the loan in years ***/
                try {
                    // Get string number of years and convert it into a number
                    totalYears = Integer.parseInt(totalYearsTF.getText());
                    } //Verify Loan Length input is numeric
                catch (NumberFormatException n) {
                    JOptionPane.showMessageDialog(null, "Invalid number... Please Re-Enter the Number of Years");
                // Test if Value is less than 1
                if (totalYears < 1) {
                    JOptionPane.showMessageDialog(null, "Invalid Input... Years of Loan must be greater than 0!");
                /*** Get Input for Interest Rate ***/
                try {
                    // Get Interest Rate and convert it into a Number
                    inputInterestRate = Double.parseDouble(interestRateTF.getText());
                //Verify Interest Rate input is numeric
                catch (NumberFormatException n) {
                    JOptionPane.showMessageDialog(null, "Invalid number... Please Re-Enter Interest Rate");
                // Test if Value is less than 1
                if (inputInterestRate < 1) {
                    JOptionPane.showMessageDialog(null, "Invalid Input... Interest Rate must be greater than 0!");

                // Do the Math and Output the Results  For User Inputted Values
                totalMonths = totalYears * 12;                  // Calculate total months of the loan term
                interestRate = inputInterestRate / (12 * 100);  // Get the monthly interest rate

                // Calculate Monthly Payment, Loan Total Amount and Total Interest Paid
                monthlyPayment = loanAmount * (interestRate / (1 - Math.pow(1 + interestRate, -totalMonths)));
                totalPaid = (monthlyPayment * totalMonths); //Calculates total amount that will be paid on the loan
                totalInterestPaid = (monthlyPayment * totalMonths) - loanAmount;    //Calulates total interest paid.

                // Display Output //
                monthlyPaymentTF.setText("" + money.format(monthlyPayment));        //Display monthly payment
                totalInterestPaidTF.setText("" + money.format(totalInterestPaid));  //Display total interest paid
                totalPaidFT.setText("" + money.format(totalPaid));                  // Display total loan cost
                new PieChart2();
            } //End if calculateButton was pressed
        } // End Method
    } //End Class

    // Begin Graph Code

    //Action Listener for view payment button
    public class viewPaymentsListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            newLoanAmount =  loanAmount;                                // Set Initial New Loan Amount
            if (e.getSource() == viewPaymentsButton) {                  // Begin If Pressed Loop
                paymentNumber = 0;                                      // Set Payment Counter
                while (totalMonths > 0) {                               // Begin Displying Values Loop
                    interestPaid = newLoanAmount * interestRate;        // Seperate interest from monthly payment
                    principlePaid = monthlyPayment - interestPaid;      // Seperate principle from monthly payment
                    newLoanAmount = newLoanAmount - principlePaid;      // Redefine value for newLoanAount
                    paymentNumber++;                                    // Increase payment number for display
                    totalMonths--;                                      // Decrease Months as payments are made
                    //Output loans Current Ballance and Interest Paid
                    myOutputArea.append("   " + paymentNumber + "                         "
                                        + money.format(newLoanAmount) + "                    "
                                        + money.format(interestPaid) + "\n\r");
                } //End Display Loop
            } //End If Pressed Loop
        } // End Method
    } // End Class

/************************* Start Up the Program *******************************/
    public static void main(String[] args) {
       new buildInterface();  //Starts the calculator
       //new PieChart2();
    } // End of Main Method
} // End buildInterface Class


PieChart2 Code

package javaprogramming421;

import java.awt.*;
import javax.swing.*;

public class PieChart2 extends JFrame  {
    JPanel panel2 = new JPanel(new BorderLayout());
    JTabbedPane jTabbedPane = new JTabbedPane();
    double graphLoanAmount, graphInterestPaid;

    public PieChart2() {
	setSize(330, 230); // set window title and size
        setLocation(750, 750);
        Container pane = getContentPane();
        pane.add(jTabbedPane, BorderLayout.CENTER);
        JPanel panel = new JPanel(new FlowLayout());
        ChartPanel chart = new ChartPanel(); // Add chartPanel to this panel
        panel2.add(chart, BorderLayout.CENTER);
        jTabbedPane.addTab(null, panel2);
    // Create an instance of our JFrame
    public static void main(String args[]) {
        PieChart2 pie = new PieChart2();
class ChartPanel extends JPanel {
    public void paintComponent(Graphics g) {
        g.fillArc (80,15,150,150,0,180);

Also if there is a somewhat easy way to move the chart display from the seperate window into the same JPanel use for the calculator, I could use some help there.

Is This A Good Question/Topic? 0
  • +

Replies To: Help needed with a pie chart

#2 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3550
  • View blog
  • Posts: 16,190
  • Joined: 20-September 08

Re: Help needed with a pie chart

Posted 09 January 2011 - 02:06 PM

It's an instance of ChartPanel you should probably be using. Make it a standalone class first and then add methods to pass parameters to it
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1