Man, my rookie status os showing on this one...

For the life of me, I cannot determine why my graphics panel section is not working to correctly display my Pie Chart....

I have the output broken down, and the variables exist... It runs looking for Annuities.csv in the C:\temp folder...
Once loaded, breaks down an annuity based on Monthly deposit, interest earned, and final balance (per month).

I am trying to add a simple pie chart showing how much of the finalBal of the annuity is gained from monthly deposits (mDepositterm12) and how much is from InterestEarned. I cannot get the variables from my code to work, and I am missing something very fundimental here, but I need a bit of guidance.

Any helpers out there tonight????

Code blocks are created by indenting at least 4 spaces
... and can span multiple lines




    Save in notepad as .CSV file, and select when running
    ========Annuties.csv=========

    5,0.050
    6,0.060
    7,0.0625
    10,0.070
    15,0.075
    20,0.078
    25,0.080
    30,0.085

    =============================
    */

    //IMPORT JAVA LIBRARIES
    import java.awt.*;
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.UIManager;
    import javax.swing.UIManager.*;
    import javax.swing.UnsupportedLookAndFeelException;


    //START CODE


    //EXTEND THE JFrame
    public class AnnuityWeek5 extends JFrame {

    //JPanel
        public JPanel panel = null;
    //PROGRAM DESC LABEL TO OUTPUT A MESSAGE TO THE PANEL
        public JLabel programLabel = null;
    //ANNUITY LABEL AND TEXT FIELD
        public JLabel annuityLabel = null;
        public JTextField annuityTextField = null;
    //TERM iRate AND TEXT FIELD
        public JLabel interestLabel = null;
        public JTextField interestTextField = null;
    //TERM LABEL AND TEXT FIELD
        public JLabel termLabel = null;
        public JTextField termTextField = null;
    //TEXT AREA FOR SOLUTION
        public JTextArea solution = null;

                        //public JLabel chartTopLabel = null;


    //BUTTONS
        public JButton calcButton = null;
        public JButton resetButton = null;
        public JButton quitButton = null;
    //CREATE THE JComboBox and SET INDEX =0
        JComboBox myComboBox;
        int selectedIndex = 0;
    //DATA VARIABLES INITIALIZE
        public double mDeposit;
        public double iRate;
        public double term;
        public double monthlyiRate;
        public double[][] annuities = new double[8][2];

    //MAIN APP WINDOW WIDTH AND HEIGHT
        public static int WINDOW_WIDTH  = 525;
        public static int WINDOW_HEIGHT = 550;

    //MAIN STATIC VOID = AnnuityWeek5

        public static void main(String[] args) {
            AnnuityWeek5 mort = new AnnuityWeek5();


    //UTILIZING THE NIMBUS LOOK AND FEEL
            try {
                for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (UnsupportedLookAndFeelException e) {
                // handle exception
            } catch (ClassNotFoundException e) {
                // handle exception
            } catch (InstantiationException e) {
                // handle exception
            } catch (IllegalAccessException e) {
                // handle exception
            }

            mort.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            mort.setTitle("<***===|David's Annuity Calculator|===***>");
            mort.setVisible(true);
        }

    //JAVA OBJECT CONSTRUCTOR METHOD
        public AnnuityWeek5() {
            initialize();
        }

        public void initialize() {

    //LOAD THE DATA FOR THE TERM AND RATES FROM Annuity.csv
            this.readRates();

    //INITIALIZE THE FRAME
            this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

    //ADDING THE PANEL TO ADD ELEMENTS
            this.add(getPanel());
            getPanel().setLayout(null);

    //ADD ANNUITY PROGRAM DESC LABEL
            programLabel = new JLabel("Please Enter a Desposit Amount and Select a Term/Rate for Calculation:");
            programLabel.setBounds(40, 20, 500, 20);
            getPanel().add(programLabel);

    //MONTHLY DEPOSIT LABEL AND FIELD
            annuityLabel = new JLabel("Monthly Desposit $");
            annuityLabel.setBounds(40, 60, 120, 20);
            getPanel().add(annuityLabel);

            annuityTextField = new JTextField();
            annuityTextField.setBounds(155, 60, 100, 20);
            getPanel().add(annuityTextField);

            myComboBox = new JComboBox();

    //SCROLLING FIELD TO OUPUT BREAKDOWN DATA 

            for (int i = 0; i < 8; i++) {
                DecimalFormat df = new DecimalFormat("##");
                DecimalFormat pf = new DecimalFormat("##.##%");

                StringBuilder sb = new StringBuilder();
                sb.append("Interest Rate " + pf.format(annuities[i][1]));
                sb.append(" \tfor " + df.format(annuities[i][0]) + " years");

                myComboBox.addItem(sb.toString());
            }
    //MyComboBox PLACEMENT IN THE PANEL
            myComboBox.setBounds(280, 60, 200, 20);
            myComboBox.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    selectedIndex = myComboBox.getSelectedIndex();
                }
            });
            getPanel().add(myComboBox);


    //SETUP THE JTextArea TO OUTPUT THE DATA
            solution = new JTextArea();
            solution.setForeground(Color.black);
            solution.setEditable(false);

            solution.setText("");
            getPanel().add(solution);

            JScrollPane scrollPane = new JScrollPane(solution);
            scrollPane.setBounds(25, 140, 460, 350);
            getPanel().add(scrollPane);

    //BEGIN PLACING BUTTONS FOR THE GUI

    //CODE FOR THE CALCULATION BUTTON
            calcButton = new JButton();
            calcButton.setBackground(new Color(30, 144, 255));
            calcButton.setForeground(Color.white);
            calcButton.setText("Calculate");
            calcButton.setBounds(30, 100, 120, 20);
    //CREATE THE ACTION FOR THE CALCULATION BUTTON
            calcButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    DecimalFormat df = new DecimalFormat("$###,###,###.00");
                    DecimalFormat pf = new DecimalFormat("###.##%");
                         DecimalFormat mf = new DecimalFormat("##");

    // GRAB THE DATA REQUIRED FROM THE TEXT FIELDS
                    mDeposit = parseDouble(annuityTextField.getText());
                    iRate = annuities[selectedIndex][1];
                    term = annuities[selectedIndex][0];


    /*==============================================================
         Start the AnnutityTotal Calculation...
        Calculate the Annuity based on the term, iRate,and mDeposit:
                 A= P[(1+ (r/n)^(n*t)-1]
                   --------------------
                           (r/n)
         Annuity Formula Calculation
    ================================================================
    */
                    double x = ( 12 * term );
                    double intCalc = ( iRate / 12 );
                    double deposit = mDeposit * (Math.pow(1+(intCalc),(x))-1)/(intCalc);



                    solution.append("");
                    solution.append("\n*******************************************");
                    solution.append("********************************************\n");
                solution.append("************************************Annutiy ");
                    solution.append("Details***********************************\n");
                   solution.append("*******************************************");
                   solution.append("********************************************\n");
                solution.append("   Monthly Deposit Amount " + df.format(mDeposit) + "\n");
                solution.append("   Duration(years) " + Double.toString(Math.round(term)) + "\n");
                solution.append("   Interest Rate " + pf.format(iRate) + "\n");
                    solution.append("\n");
                    solution.append("   Let's break it down per mothly depost:\n");
                    solution.append("\n");
                solution.append("Month\tStart Bal\tDeposit\tInterest\tFinal Bal\n");
                    solution.append("=========\t=========\t=========\t=========\t=========\n");

    //START MONTHLY LOOP-------------------------------------------------------------------
                    double balance = 0;

                    for (int i = 0; i < (term * 12); i++) {
                        int month = i + 1;
                        double interestEarned = balance * iRate / 12;
                        double endingBal = balance + interestEarned + mDeposit;

                        String row = String.format("%d\t%s\t%s\t%s\t%s\n",
                                month,
                                df.format(balance),
                                df.format(mDeposit),
                                df.format(interestEarned),
                                df.format(endingBal));
                        solution.append(row);
                        balance = endingBal;
                    }
    //END OF MONTHLY LOOP-----------------------------------------------------------------

        // ****====HAVING FUN WHILE LEARNING====****                 
    //OUTPUT THE FINAL BALANCE WITH A NICE FORMAT FOR THE BOTTOM OF THE SCREEN 

                         double finalBal = balance;
                         double totalMonths = term * 12;
                         solution.append("=========\t=========\t=========\t=========\t=========\n");
                         solution.append("Month\tStart Bal\tDeposit\tInterest\tFinal Bal\n");
                         solution.append("\n*******************************************");
                         solution.append("*********************************************");
                         solution.append("\n  You would have " + df.format(finalBal));
                         solution.append(" in total annuity savings over your " + mf.format(totalMonths) + " month term!");
                         solution.append("\n*******************************************");
                         solution.append("*********************************************");


                         repaint();

                         graphicsPanel();
                }
            });
            getPanel().add(calcButton);

    // CODE FOR THE RESET BUTTON
            resetButton = new JButton();
            resetButton.setBackground(new Color(139, 139, 137));
            resetButton.setForeground(Color.white);
            resetButton.setText("Clear Data");
            resetButton.setBounds(195, 100, 120, 20);

            resetButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    annuityTextField.setText("");
                    solution.setText("");
                }
            });

            getPanel().add(resetButton);

    // CODE FOR THE QUIT BUTTON
            quitButton = new JButton();
            quitButton.setBackground(new Color(200, 100, 80));
            quitButton.setForeground(Color.white);
            quitButton.setText("Exit");
            quitButton.setBounds(360, 100, 120, 20);
            quitButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    setVisible(false);
                    System.exit(0);
                }
            });
            getPanel().add(quitButton);
        }

    //SETUP THE MAIN PANEL
        public JPanel getPanel() {
            if (panel == null) {
                panel = new PanelClass();
                panel.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
                panel.setBackground(new Color(205, 201, 201));  
    //SET THE BACKGROUND COLOR...
            }

            return panel;
        }

     /*
     * START THE PIE CHART TO SHOW THE DEPOSIT vs. INTEREST
     */

     GraphicsPanel graphicsPanel = null;
        JDialog graphicsDialog = null;

        /**
         * This is where I draw the graphics. For the amount of interest owned and
         * compared to the loan amount (principal), The pie chart shows interest(red) vs principal(blue)
         */
        public void graphicsPanel(){
            if(graphicsDialog != null && graphicsDialog.isVisible()){


                graphicsPanel.setVisible(false);            
                graphicsDialog.setVisible(false);
                graphicsPanel = null;
                graphicsDialog = null;
            }

            graphicsDialog = new JDialog();
          graphicsPanel = new GraphicsPanel();

    //DECLARE THE VARIABLES TO BE USED IN THE PIE CHART
              double balance;
              double depositEarned = mDeposit*term*12;
            double interestEarned = balance - depositEarned;


            graphicsPanel.setInterestEarned(interestEarned);
              graphicsPanel.setDepositEarned (depositEarned);


    // DECLARE A NEW WINDOW FOR THE PIE CAHRT TO SHOW ON

            graphicsDialog.add(graphicsPanel);
          graphicsDialog.setModal(true);   
          graphicsDialog.setSize(400,550);
            graphicsDialog.setTitle("<***===|Annuity Chart Breakdown|===***>");    
          graphicsDialog.setVisible(true);

        }

    // CREATE THE WINDOW
        class GraphicsPanel extends JPanel {
            double interestEarned;
            double depositEarned;


            public void paintComponent(Graphics g){
    // SET THE BACKGROUND AS GREY
                Graphics2D g2 = (Graphics2D) g;
                g2.setColor(new Color(205, 201, 201));
                g2.fillRect(0, 0, 400, 550);
    // ADD LABELS and TEXT TO THE PIE CHART WINDOW
                    JLabel chartTopLabel = null;

            g2.setColor(Color.black);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            Font font = new Font("Serif", Font.BOLD, 16);
            g2.setFont(font);
            g2.drawString("Annuity Deposits Vs. Interest Earned", 70, 20);



    // MAKE TWO SMALL SQUARES WITH LABELS FOR THE COLOR LEDGEND

            g2.setColor(Color.yellow);
            g2.fill3DRect(200, 420, 15, 15,true);
                    g2.setColor(Color.black);
                    g2.drawString("= Annuity Deposits", 230, 435);

            g2.setColor(Color.green);
            g2.fill3DRect(200, 450, 15, 15,true);
                    g2.setColor(Color.black);
                    g2.drawString("= Interest Earned", 230, 465);

    // SET COLOR, SIZE, AND ARC POSITION FOR THE PIE CHART

                double pieInterest = interestEarned/balance;
                int arcIntStartPoint = (int)(pieInterest * 360.);
                g2.setColor(Color.green);
                g2.fillArc(50, 50, 300,300, 0, arcIntStartPoint);
                g2.setColor(Color.cyan);
                g2.fillArc(50,50,300,300,arcIntStartPoint,360-arcIntStartPoint);
            }

            public void setInterestEarned(double interestEarned){
                this.interestEarned = interestEarned;
            }

            public void DepositEarned(double depositEarned){
                this.DepositEarned = depositEarned;
            }
        }

        class PanelClass extends JPanel {
        }

       public double monthlyiRate(double mDeposit, 
                double iRate, double term) {

            double deposit = 
              mDeposit * (iRate) * (Math.pow((iRate + 1), term)) / (Math.pow((iRate + 1), term) - 1);

            return deposit;
        }

    //READ THE DATA FROM Annuity.csv
    //USE tokenizer TO GRAB THE DATA
    //AND LOAD THE DATA INTO THE BUFFER
        public void readRates() {
            try {
                String file = findFile();
                BufferedReader buffer = new BufferedReader(new FileReader(file));

                String line;
                int row = 0;
                int col = 0;

                while ((line = buffer.readLine()) != null) {
                    StringTokenizer tokenReader = new StringTokenizer(line, ",");
                    while (tokenReader.hasMoreTokens()) {
                        annuities[row][col++] = 
                                Double.parseDouble(tokenReader.nextToken());
                    }
                    row++;
                    col = 0;
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }

     //THIS CODE IS BARROWED AND MENT TO ALLOW THE USER
     //TO LOCATE THE Annuity.csv ON THEIR LOCAL MACHINE  

        public String findFile() {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(new File("c:\\temp"));
            /*
             * The result is one of the following: APPROVE_OPTION, 
             * CANCEL_OPTION, or ERROR_OPTION
             * We ignore it here, but for practical applications 
             * we would want to handle this.
             */
            int result = fileChooser.showOpenDialog(this);
            // Get the full path of filename that was selected
            String fileName = fileChooser.getSelectedFile().getPath();
            return fileName;
        }

        public static double parseDouble(String val) {
            double value = 0;
            try {
                // We test to see if there is a dollar sign, if there
                // is we use the currency number formater, otherwise just
                // the number formatter.
                if (val.indexOf('$') > -1) {
                    // we need to use the currency expression
                    value = NumberFormat.getCurrencyInstance().
                            parse(val).doubleValue();
                } else {
                    value = NumberFormat.getNumberInstance().
                            parse(val).doubleValue();
                }
            } catch (java.text.ParseException e) {
                // We generate an error here, we can add a JOptionDialog to display the
                // text and the error
                JOptionPane.showMessageDialog(null,
                        "Error in parsing " + val + ". Please check your entry",
                        "Data Entry Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            return value;

        }

        public static double parsePercent(String val) {
            boolean isPercent = false;
            double value = 0;
            try {
                if (val.indexOf('%') > -1) {
                    value = NumberFormat.getPercentInstance().
                            parse(val).doubleValue();
                    isPercent = true;
                } else {
                    value = NumberFormat.getNumberInstance().
                            parse(val).doubleValue();
                }
            } catch (java.text.ParseException e) {
                JOptionPane.showMessageDialog(null, 
                        "Error in parsing " + val + ". Please check your entry",
                        "Data Entry Error", JOptionPane.ERROR_MESSAGE);
            }

            if (!isPercent) {
                value = value / 100.0;
            }

            return value;
        }

    }
    //END CODE

Any advice on what I am missing here is greatly appreciated.... For now I am back to the Drawing Board
~Dave

315 - 411 is where the issue is...

I just need that darn pie chart to get the correct amounts based on the variables used...

Is the variables data Blank????

This article has been dead for over six months. Start a new discussion instead.