8 Replies - 1360 Views - Last Post: 12 July 2010 - 07:33 AM Rate Topic: -----

#1 Guest_davedio*


Reputation:

java pie chart

Posted 09 July 2010 - 01:39 PM

I am wondering if someone could tell me why the pie chart only has 3 slices when it should be displaying 6?
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class MortgageCalculator extends JFrame implements ActionListener,
		ItemListener {

	/**
	 * the following will declare the variables
	 */
	private static final long serialVersionUID = 1L;
	private double userAmount = -1.0;
	private double interest = -1.0;
	private int userTerm = -1;
	String[] annualInterestRate = {"5.35", "5.50", "5.75"};
	String[] selectedYears = { "7", "15", "30" };
	private NumberFormat fmt = NumberFormat.getInstance();
	private JTextField numberFormat;
	private String[] term;
	private String[] rate;
	Color uneasyBeingGreen = new Color(0xCC, 0xCC, 0x99);
	Color zuzusPetals = new Color(0xCC, 0x66, 0xFF);
	Color zootSuit = new Color(0x66, 0x66, 0x99);
	Color sweetHomeAvocado = new Color(0x66, 0x99, 0x66);
	Color shrinkingViolet = new Color(0x66, 0x66, 0x99);
	Color miamiNice = new Color(0x33, 0xFF, 0xFF);
	Color inBetweenGreen = new Color(0x00, 0x99, 0x66);
	Color norwegianBlue = new Color(0x33, 0xCC, 0xCC);
	Color purpleRain = new Color(0x66, 0x33, 0x99);
	Color freckle = new Color(0x99, 0x66, 0x33);


	public void setNumberFormat(double numberFormat) {
		this.numberFormat = txtAmount;
	}

	public JTextField getNumberFormat() {
		return numberFormat;
	}

	/*
	 * the following will instantiate the GUI Component for the different rows
	 */

	/*
	 * row1 will have the loan amount, drop box, user rate term
	 */

	JPanel row1 = new JPanel();
	JLabel lblAmount = new JLabel(" Mortgage: $", JLabel.LEFT);
	JTextField txtAmount = new JTextField(10);

	// combo for interest & term

	JLabel lblcombo = new JLabel("Term/Interest");
	String cboData[] = { "Select Term", "7 years and 5.35%",
			"15 years and 5.50%", "30 years and 5.75%" };
	JComboBox comboTermInterest = new JComboBox(cboData);

	// term

	JLabel lblTerm = new JLabel("Term:");
	JTextField txtTerm = new JTextField(3);

	// interest rate Field

	JLabel lblRate = new JLabel("Interest Rate:");
	JTextField txtRate = new JTextField(3);

	// payment Field

	JLabel lblPayment = new JLabel("Payment:");
	JTextField txtPayment = new JTextField(10);

	/*
	 * row 2 will be used for the labels for the scheduled payments string and
	 * the Scroll box for the payment list
	 */

	JPanel row2 = new JPanel(new BorderLayout());
	String pad = "                           ";
	JLabel lblHeader = new JLabel("Payment #" + pad + "Balance:" + pad
			+ "Principle Paid:" + pad + "Interest Paid:" + pad + "New Balance:");
	JTextArea txtResults = new JTextArea(10, 3);
	JScrollPane textPane = new JScrollPane(txtResults);

	// row 3 is used for the buttons to Calculate, clear and exit the program

	JPanel row3 = new JPanel(new GridLayout(1, 3, 0, 1));
	JButton calculateButton = new JButton("Calculate");
	JButton clearButton = new JButton("Clear");
	JButton exitButton = new JButton("Exit");
	JButton pieButton = new JButton("Chart");

	// Build GUI

	public MortgageCalculator() {
		super("Mortgage Calculator");
		initialize();
		setBounds(50, 150, 200, 50);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		row1.add(lblAmount);
		row1.add(txtAmount);
		row1.add(lblcombo);
		row1.add(comboTermInterest);
		row1.add(lblTerm);
		row1.add(txtTerm);
		row1.add(lblRate);
		row1.add(txtRate);
		row1.add(lblPayment);
		row1.add(txtPayment);
		txtPayment.setText("0.0");
		txtPayment.setEditable(false);
		txtResults.setEditable(false);
		txtTerm.setEditable(true);
		txtRate.setEditable(true);
		textPane.setPreferredSize(new Dimension(510, 200));

		row2.add(lblHeader, BorderLayout.NORTH);
		row2.add(textPane, BorderLayout.CENTER);

		// Create Calculate button and add listener
		comboTermInterest.addActionListener(this);
		comboTermInterest.getAction();
		calculateButton.addActionListener(this);
		clearButton.addActionListener(this);
		exitButton.addActionListener(this);
		pieButton.addActionListener(this);
		txtAmount.requestFocus();

		row3.add(exitButton);
		row3.add(clearButton);
		row3.add(calculateButton);
		row3.add(pieButton);
		// This will set the layout of the GUI as to the locations of the
		// different rows

		getContentPane().add(row1, BorderLayout.NORTH);
		getContentPane().add(row2, BorderLayout.CENTER);
		getContentPane().add(row3, BorderLayout.SOUTH);
		pack();
	}

	private void initialize() {
		term = loadTerm("loadterm.txt");
		rate = loadRate("loadrate.txt");
		fmt.setGroupingUsed(true);
		fmt.setMaximumFractionDigits(2);
		fmt.setMinimumFractionDigits(2);
	}

	private String[] loadTerm(String filename) {
		String[] retval = new String[3];
		int index = 0;
		try {
			// If you are not an applet, uncomment these two lines and comment
			// out the other 2.
			File fromFile = new File(filename);
			BufferedReader reader = new BufferedReader(new FileReader(fromFile));
			String line = reader.readLine();
			while (line != null) {
				retval[index] = line;
				line = reader.readLine();
				index++;
			}
			return retval;
		} catch (IOException e) {
			System.err.println(e.getMessage());
			return null;
		}
	}

	private String[] loadRate(String filename) {
		String[] retval = new String[3];
		int index = 0;
		try {
			// If you are not an applet, uncomment these two lines and comment
			// out the other 2.
			File fromFile = new File(filename);
			BufferedReader reader = new BufferedReader(new FileReader(fromFile));
			String line = reader.readLine();
			while (line != null) {
				retval[index] = line;
				line = reader.readLine();
				index++;
			}
			return retval;
		} catch (IOException e) {
			System.err.println(e.getMessage());
			return null;
		}
	}

	// Actions for combo box selection
	public String getField(JTextField field) {
		return field.getText();
	}

	public void itemStateChanged(ItemEvent event) {
		int index = comboTermInterest.getSelectedIndex();
		if (index == 0) {
			interest = 5.35;
			userTerm = 7;

		} else if (index == 1) {
			interest = 5.50;
			userTerm = 15;

		}
		if (index == 2) {
			interest = 5.75;
			userTerm = 30;
		}

	}

	// Define actions performed for buttons

	public void actionPerformed(ActionEvent e) {
		/*
		 * The following code will load the values of the preselected loans into
		 * the calculation
		 */
		int index = comboTermInterest.getSelectedIndex();
		if (index == 1) {
			txtRate.setText("5.35");
			txtTerm.setText("7");
			txtTerm.setEditable(false);
			txtRate.setEditable(false);

		}
		if (index == 2) {

			txtRate.setText("5.50");
			txtTerm.setText("15");
			txtTerm.setEditable(false);
			txtRate.setEditable(false);

		}
		if (index == 3) {
			txtRate.setText("5.75");
			txtTerm.setText("30");
			txtTerm.setEditable(false);
			txtRate.setEditable(false);
		}

		if (e.getSource() == clearButton) {
			// clear fields
			txtTerm.setVisible(true);
			txtRate.setVisible(true);
			txtTerm.setEditable(true);
			txtRate.setEditable(true);
			comboTermInterest.setSelectedIndex(0);
			txtAmount.setText("");
			txtPayment.setText("0.0");
			txtTerm.setText("");
			txtRate.setText("");
			userAmount = (0.0);
			txtResults.setText("");
			txtAmount.requestFocus();
			txtTerm.setEditable(true);
			txtRate.setEditable(true);
		}
		if (e.getSource() == exitButton) {
			System.exit(0);
		}
		/*
		 * This section of the code will load the pie chart that is referenced
		 * from Chip Dickson
		 */

		if (e.getSource() == pieButton) {
			PiePanel pie2 = new PiePanel(rate.length);
			PiePanel pie3 = new PiePanel(term.length);
			pie2.addSlice(uneasyBeingGreen,
					Float.parseFloat(annualInterestRate[0]));
			pie2.addSlice(freckle, Float.parseFloat(annualInterestRate[1]));
			pie2.addSlice(zootSuit,
					Float.parseFloat(annualInterestRate[2]));
			pie3.addSlice(purpleRain, Float.parseFloat(selectedYears[0]));
			pie3.addSlice(inBetweenGreen, Float.parseFloat(selectedYears[1]));
			pie3.addSlice(norwegianBlue, Float.parseFloat(selectedYears[2]));
			final JFrame frame = new JFrame();
			frame.getContentPane().add(pie2);
			frame.getContentPane().add(pie3);
			frame.pack();
			frame.setSize(500, 500);
			frame.setVisible(true);
		}
		/*
		 * This will do all the calculations and call the Mortgagepayment class
		 * to do all the calculations, and to display the the monthly payments
		 * and balance of the loan for both the preselected and the user
		 * amounts.
		 */

		if (e.getSource() == calculateButton) {
			try {

				String tStr = txtAmount.getText();
				userAmount = Double.parseDouble(tStr);
				String rStr = txtRate.getText();
				interest = Double.parseDouble(rStr);
				userTerm = Integer.parseInt(txtTerm.getText());
				String tStr1 = txtTerm.getText();
				userTerm = Integer.parseInt(tStr1);

			} catch (NumberFormatException nfe) {
				popupError("Enter Valid Information");
				return;
			}

			double loanAmount = Double.parseDouble(txtAmount.getText());
			interest = Double.parseDouble(txtRate.getText()) / 100;
			userTerm = Integer.parseInt(txtTerm.getText());
			int years = Integer.parseInt(txtTerm.getText());

			Mortgagepayment formula = new Mortgagepayment(loanAmount, interest,
					years);

			txtPayment.setText(formula.getpayment());

			Mortgagepayment formula1 = new Mortgagepayment(loanAmount,
					interest, years);
			txtResults.setText(formula1.getCalculationTableAsString());
		}
	}

	private void popupError(String error) {
		JOptionPane.showOptionDialog(null, error, "Warning",
				JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
				null, null);
	}

	public static void main(String[] args) {

		new MortgageCalculator().setVisible(true);

	}

}


here is some more code

import java.text.NumberFormat;

public class Mortgagepayment {
	/*
	 * The following code is referenced from Charles Dickson. this will declare the variables.
	 */
	private double userTerm = -1.0;
	private double userInterest = -1.0;
	private double userAmount = -1.0;
	private double selectedRate = -1.0;
	private double loanAmount = -1.0;
	private double interest = -1.0;
	private int numofPaymentsYears = -1;
	private double payment;
	private double total;
	private int years = -1;
	private double[] interestPaid = null;
	private double[] balance = null;
	private double[] principalPaid = null;
	private double[] previousBalance = null;
	private NumberFormat fmt = NumberFormat.getInstance();
	private double paymentout;

	public Mortgagepayment(double loanAmount, double selectedRate, int year) {
		this.loanAmount = loanAmount;
		this.selectedRate = selectedRate;
		this.years = year;
		interest = selectedRate / 12;
		numofPaymentsYears = year * 12;
		interestPaid = new double[numofPaymentsYears];
		principalPaid = new double[numofPaymentsYears];
		balance = new double[numofPaymentsYears];
		previousBalance = new double[numofPaymentsYears];
		/*
		 * the following will set number format
		 */
		fmt.setGroupingUsed(true);
		fmt.setMaximumFractionDigits(2);
		fmt.setMinimumFractionDigits(2);
		calculatepayment();
		buildCalculationTable();
		calculatetotal();
	}

	/*
	 * The following will do the calculations needed for the program
	 */
	private void calculatepayment() {
		payment = (loanAmount * interest
				/ (1 - Math.pow(1 / (1 + interest), years * 12)));
	}
	private void calculatetotal() {
		total = payment * (years *12) - loanAmount ;
	}
	public String gettotal()  {
		return fmt.format(total);
	}

	public String getpayment() {
		return fmt.format(payment);
		}
	public String getpaymentout(){
		return fmt.format(paymentout);
	}

	public void buildCalculationTable() {
		int paymentNumber = 0;
		double mnthBalance = loanAmount;
		double monthlyInt;
		double princ;
		while (paymentNumber < numofPaymentsYears) {
			previousBalance[paymentNumber] = mnthBalance;
			monthlyInt = mnthBalance * (selectedRate / 12);
			princ = payment - monthlyInt;
			interestPaid[paymentNumber] = monthlyInt;
			principalPaid[paymentNumber] = princ;
			mnthBalance = mnthBalance - princ;
			balance[paymentNumber] = mnthBalance;
			paymentNumber++;
		}
	}

	public String getCalculationTableAsString() {
		StringBuffer buffer = new StringBuffer();
		int paymentNumber = 0;
		buffer
				.append("Payment #\tBalance\t\t   Principle Paid   \t  Interest Paid\t\t   New Balance \n");
		while (paymentNumber < numofPaymentsYears) {
			buffer.append((paymentNumber + 1) + "\t   $"
					+ fmt.format(previousBalance[paymentNumber]) + "\t\t   $"
					+ fmt.format(principalPaid[paymentNumber]) + "\t\t   $"
					+ fmt.format(interestPaid[paymentNumber]) + "\t\t   $"
					+ fmt.format(balance[paymentNumber]) + "\n");
			if ((paymentNumber + 1) % 12 == 0) {
				}

			paymentNumber++;
		}
		return buffer.toString();
	}

	public int getNumofPaymentsYears() {
		return numofPaymentsYears;
	}

	public int getyears() {
		return years;
	}

	public void setyears(int years) {
		this.years = years;
		numofPaymentsYears = years * 12;
		// need to re-allocate all the arrays
		interestPaid = new double[numofPaymentsYears];
		principalPaid = new double[numofPaymentsYears];
		balance = new double[numofPaymentsYears];
		previousBalance = new double[numofPaymentsYears];
		// calculate the new values
		calculatepayment();
		buildCalculationTable();
	}

	public double getloanAmount() {
		return loanAmount;
	}

	public void setloanAmount(double loanAmount) {
		this.loanAmount = loanAmount;
		calculatepayment();
		buildCalculationTable();
	}

	public double getselectedRate() {
		return selectedRate;
	}

	public void setselectedRate(double selectedRate) {
		this.selectedRate = selectedRate;
		interest = selectedRate / 12;
		calculatepayment();
		buildCalculationTable();

	}
}



here is the code for the pie slice
import java.awt.Color;

/*
 * PieSlice.java
 */
/** The author of this code is also referenced to Chip Dickson
 * @author Chip Dickson
 *
 * All right reserved. 
 */
class PieSlice
{
    Color color = Color.CYAN;
    float size = 0;

    PieSlice(Color pColor, float pSize)
    {
        color = pColor;
        size = pSize;
    }
}


here is the code for the pie pannal
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JPanel;

/*
 * PiePanel.java 
 */
/**This pie panel was taken from the sample charts that Chip 
 * posted and is referenced to Chip Dickson
 * @author Chip Dickson All right reserved.
 */
public class PiePanel extends JPanel
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private PieSlice[] slice;
    private int current = 0;
    private float totalSize = 0;
    private Color background;

    public PiePanel(int sliceCount)
    {
        super();
        slice = new PieSlice[sliceCount];
        background = getBackground();
    }

	public void addSlice(Color sColor, float sSize)
    {
        if (current <= slice.length)
        {
            slice[current] = new PieSlice(sColor, sSize);
            totalSize += sSize;
            current++;
        }
    }

    public void paintComponent(Graphics comp)
    {
        super.paintComponent(comp);
        Graphics2D comp3D = (Graphics2D) comp;
        int width = getSize().width - 10;
        int height = getSize().height - 15;
        int xInset = 5;
        int yInset = 5;
        if (width < 5)
            xInset = width;
        if (height < 5)
            yInset = height;
        comp3D.setColor(background);
        comp3D.fillRect(0, 0, getSize().width, getSize().height);
        comp3D.setColor(Color.lightGray);
        Ellipse2D.Float pie = new Ellipse2D.Float(xInset, yInset, width, height);
        comp3D.fill(pie);
        float start = 0;
        for (int i = 0; i < slice.length; i++)
        {
            float extent = slice[i].size * 360F / totalSize;
            comp3D.setColor(slice[i].color);
            Arc2D.Float drawSlice = new Arc2D.Float(xInset, yInset, width, height, start, extent,
                    Arc2D.Float.PIE);
            start += extent;
            comp3D.fill(drawSlice);
        }
    }
}


then I have 2 text documents one with the interest rates of
5.35,
5.50,
5.75
the next text document has the years on it 7,
15,
30

Is This A Good Question/Topic? 0

Replies To: java pie chart

#2 bcranger  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,199
  • Joined: 01-February 10

Re: java pie chart

Posted 09 July 2010 - 01:52 PM

I believe it is because you are creating two PiePanels

pie2 and pie3...

one moment im going to run the code

could you attach the text files?
Was This Post Helpful? 0
  • +
  • -

#3 Guest_davedio*


Reputation:

Re: java pie chart

Posted 10 July 2010 - 09:15 AM

I would have attached the files but I did not know how to attach them in this forum, you could just creat 2 text documents one labeled loadterm.txt and the other loadrate.txt
loadterm document will have the term
7 years
15 years
30 years

load rate document will have
5.35%
5.50%
5.75%
Was This Post Helpful? 0

#4 bcranger  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,199
  • Joined: 01-February 10

Re: java pie chart

Posted 10 July 2010 - 11:43 AM

Your problem is in the PiePanel class...

Notice in your constructor, you make an ARRAY of a fixed length

slice = new PieSlice[sliceCount];



This means this array will ALWAYS have the same length.

Now look at your add pie slice method:

slice[current] = new PieSlice(sColor, sSize);



This does not change the fact that your array size is the SAME.

You should, in my opinion, use an ArrayList, as adding elements is very simple.

// taht will do it
slice.add(new PieceSlice(sColor,sSize);


Was This Post Helpful? 1
  • +
  • -

#5 Guest_davedio*


Reputation:

Re: java pie chart

Posted 10 July 2010 - 03:36 PM

How would I change this, I have tried adding the

Quote

slice.add(new PieSlice(sColor,sSize);

but it wants me to change that to

Quote

slice.length


Could you tell me how I should change this?
Was This Post Helpful? 0

#6 n8wxs  Icon User is offline

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

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

Re: java pie chart

Posted 10 July 2010 - 04:58 PM

Your chart only has 3 slices because you are limiting the number of slices to the number of interest rates or term periods contained in the text files:

...
    private void initialize() {
        term = loadTerm("loadterm.txt");
        rate = loadRate("loadrate.txt");
        fmt.setGroupingUsed(true);
        fmt.setMaximumFractionDigits(2);
        fmt.setMinimumFractionDigits(2);
    }
...



This probably not what you want but does display 6 slices... :)

...
        if (e.getSource() == pieButton) {
//            PiePanel pie2 = new PiePanel(rate.length);
            PiePanel pie2 = new PiePanel(rate.length + term.length);
//            PiePanel pie3 = new PiePanel(term.length);
            pie2.addSlice(uneasyBeingGreen,
                    Float.parseFloat(annualInterestRate[0]));
            pie2.addSlice(freckle, Float.parseFloat(annualInterestRate[1]));
            pie2.addSlice(zootSuit,
                    Float.parseFloat(annualInterestRate[2]));
//            pie3.addSlice(purpleRain, Float.parseFloat(selectedYears[0]));
//            pie3.addSlice(inBetweenGreen, Float.parseFloat(selectedYears[1]));
//            pie3.addSlice(norwegianBlue, Float.parseFloat(selectedYears[2]));
            pie2.addSlice(purpleRain, Float.parseFloat(selectedYears[0]));
            pie2.addSlice(inBetweenGreen, Float.parseFloat(selectedYears[1]));
            pie2.addSlice(norwegianBlue, Float.parseFloat(selectedYears[2]));
            final JFrame frame = new JFrame();
            frame.getContentPane().add(pie2);
//            frame.getContentPane().add(pie3);
            frame.pack();
            frame.setSize(500, 500);
            frame.setVisible(true);
        }
..


This post has been edited by n8wxs: 10 July 2010 - 05:00 PM

Was This Post Helpful? 0
  • +
  • -

#7 bcranger  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,199
  • Joined: 01-February 10

Re: java pie chart

Posted 10 July 2010 - 06:09 PM

When i said "slice.add(new PieSlice())..." I meant it would be how you would accomplish it using an ArrayList. You have to change your array to an ArrayList

// This is how you would declare it
ArrayList<PieSlice> slice = new ArrayList<PieSlice>();



You must also modify all your existing code dealing with regular arrays
Was This Post Helpful? 0
  • +
  • -

#8 Guest_davedio*


Reputation:

Re: java pie chart

Posted 12 July 2010 - 07:17 AM

Thanks, I have got it working now, but I do have one other question, one what code and where would I add the labels to the slices?

I have tried doing this

Quote

pie2.addSlice(norwegianBlue, Float.parseFloat(selectedYears[2] + "Lable here"));


but this is not correct, could you tell me the code and where to add it?
Was This Post Helpful? 0

#9 bcranger  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 252
  • View blog
  • Posts: 1,199
  • Joined: 01-February 10

Re: java pie chart

Posted 12 July 2010 - 07:33 AM

You add the Label in whatever class controls your pie slice graphics.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1