7 Replies - 3142 Views - Last Post: 06 August 2010 - 04:26 PM Rate Topic: -----

#1 Guest_Oshi*


Reputation:

Java Pie Chart

Posted 05 August 2010 - 05:20 PM

Hello,

I was wondring if someone could take a look at my program. I need help with getting my pie chart to work. I cannot seem to get the "slices" to appear. Thank you in advance!


Here is my code;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;


public class Test extends JFrame implements ActionListener
{
public static void main(String[] args)
{
Test app = new Test();
app.pack();
}
DecimalFormat twoPlaces = new DecimalFormat("#,###.00");//number format

int L[] = {7, 15, 30};
double I[] = {5.35, 5.5, 5.75};
double P, M, J, H, C, Q;
boolean manual = true;
PieChart pc = null;
JPanel panel = new JPanel ();

JRadioButton opt1 = new JRadioButton ("Manual Input", true);
JRadioButton opt2 = new JRadioButton ("Menu Selections", false);
ButtonGroup radioSelect = new ButtonGroup();


JLabel PLabel = new JLabel("mortgage amount Enter: ");
JTextField PField = new JTextField(10);//field user input for mortgage amount

JLabel LLabel1 = new JLabel("Enter the term in years: ");
JTextField LField = new JTextField(3);//field user input for term in years

JLabel ILabel1 = new JLabel("Enter the interest rate: ");
JTextField IField = new JTextField(5);//field user input for interest rate

JLabel choices = new JLabel ("Or Choose the Interest Rate and Term in Years");

JButton calcButton = new JButton("Calculate");
JButton clearButton = new JButton("Clear");
JButton exitButton = new JButton("Exit");

JTextField payment = new JTextField(10);

JLabel ILabel2 = new JLabel("Interest Rate: choose one");
String [] IChoice = {I[0] + "", I[1] + "", I[2] + ""};
JComboBox IBox = new JComboBox(IChoice);

JLabel LLabel2 = new JLabel("Term (in years): choose one");
String [] LChoice = {L[0] + "", L[1] + "", L[2] + ""};
JComboBox LBox = new JComboBox(LChoice);

JLabel amortBox = new JLabel("Amortization Table");
JTextArea ta = new JTextArea();
//JScrollPane amortScroll = new JScrollPane();//
JScrollPane amortScroll = new JScrollPane(ta, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);




public Test () //creates the GUI window
{

super(" Mortgage Calculator Week 5");
setSize(500, 400);
panel.setBackground (Color.white);
//panel.setLayout(null);
panel.setPreferredSize(new Dimension(900, 500));
setResizable(false) ;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


//Creates the container
//Container contentPane = getContentPane();
FlowLayout fresh = new FlowLayout(FlowLayout.LEFT);
BorderLayout bl = new BorderLayout();
panel.setLayout(fresh);

//identifies trigger events
calcButton.addActionListener(this);
clearButton.addActionListener(this);
exitButton.addActionListener(this);
PField.addActionListener(this);
LField.addActionListener(this);
IField.addActionListener(this);
opt1.addActionListener(this);
opt2.addActionListener(this);



//panel.setLayout(fresh);

//Options
radioSelect.add(opt1);
radioSelect.add(opt2);
panel.add(opt1);
opt1.setBackground (Color.white);
panel.add(opt2);
opt2.setBackground (Color.white);

//Manual Entries
panel.add(PLabel);
panel.add(PField);
panel.add(LLabel1);
panel.add(LField);
panel.add(ILabel1);
panel.add(IField);

//Pre-set Entries
panel.add(choices);
panel.add(ILabel2);
panel.add(IBox);
IBox.setBackground (Color.white);
panel.add(LLabel2);
panel.add(LBox);
LBox.setBackground (Color.white);

//Buttons
panel.add(calcButton);
calcButton.setBackground (Color.white);
panel.add(payment);
payment.setBackground (Color.white);
panel.add(clearButton);
clearButton.setBackground (Color.white);
panel.add(exitButton);
exitButton.setBackground (Color.white);

//Amortization Table
panel.add(amortBox);
payment.setEditable(false);
panel.add(amortScroll);
amortScroll.setPreferredSize(new Dimension(600,300));
setContentPane(panel);
setVisible(true);

//Pie Chart
pc = new PieChart(C,H);// pie chart display cut or % this just to show
JPanel piePanel = new JPanel();
piePanel.setLayout(new BorderLayout());
piePanel.add(pc);
JFrame pieFrame = new JFrame("Pie Chart");
pieFrame.setSize(310,330);
pieFrame.getContentPane().add(piePanel);
pieFrame.setVisible(true);

}// end of GUI info


public void actionPerformed(ActionEvent e)
{

Object source = e.getSource();

if (source == calcButton)
{
pc.resetPieChart(C, H);
try
{
if (manual)

Calculations_manual();

else Calculations_menu();
}

catch(NumberFormatException event)
{
JOptionPane.showMessageDialog(null, "You did not enter a number. Try again.", "ERROR", JOptionPane.ERROR_MESSAGE);
}

}



if (source == clearButton)
{
reset();
}

if (source == exitButton)
{
end();
}

if (source == opt1)
{

IBox.setEnabled(false);
LBox.setEnabled(false);
LField.setEnabled(true);
LField.setEditable(true);
IField.setEnabled(true);
IField.setEditable(true);
manual = true;

}

if (source == opt2)
{

IBox.setEnabled(true);
LBox.setEnabled(true);
LField.setEnabled(false);
LField.setEditable(false);
IField.setEnabled(false);
IField.setEditable(false);
manual = false;

}

}



public void Calculations_menu() //performs the calculations from user input
{

double P = Double.parseDouble(PField.getText());
double I = Double.parseDouble((String) IBox.getSelectedItem());
double L = Double.parseDouble((String) LBox.getSelectedItem());
double J = (I / (12 * 100));//monthly interest rate
double N = (L * 12);//term in months
double M = (P * J) / (1 - Math.pow(1 + J, - N));//Monthly Payment
String showPayment = twoPlaces.format(M);
payment.setText(showPayment);


int month = 1;

while (month <= N)
{

//performs the calculations for the amortization
double H = P * J;//current monthly interest
double C = M - H;//monthly payment minus monthly interest
double Q = P - C;//new balance
P = Q;//sets loop
month++;
//String showAmort = twoPlaces.format(H + C + Q);
//amortScroll(showAmort);
//append("Month " + month);
ta.append("Interest Paid: " + twoPlaces.format(H));
ta.append("\tPrincipal Paid: " + twoPlaces.format(C));
ta.append("\tNew Balance: " + twoPlaces.format(Q) + "\n");
}

}


public void Calculations_manual() //performs the calculations from user input
{

double P = Double.parseDouble(PField.getText());
double I = Double.parseDouble(IField.getText());
double L = Double.parseDouble(LField.getText());
double J = (I / (12 * 100));//monthly interest rate
double N = (L * 12);//term in months
double M = (P * J) / (1 - Math.pow(1 + J, - N));//Monthly Payment
String showPayment = twoPlaces.format(M);
payment.setText(showPayment);



int month = 1;

while (month <= N)
{

//performs the calculations for the amortization
double H = P * J;//current monthly interest
double C = M - H;//monthly payment minus monthly interest
double Q = P - C;//new balance
P = Q;//sets loop
month++;
//String showAmort = twoPlaces.format(H + C + Q);
//amortScroll(showAmort);
//append("Month " + month);
ta.append("Interest Paid: " + twoPlaces.format(H));
ta.append("\tPrincipal Paid: " + twoPlaces.format(C));
ta.append("\tNew Balance: " + twoPlaces.format(Q) + "\n");

}

}

// resets GUI for another calculation
public void reset ()
{
PField.setText(null);
payment.setText(null);
ta.setText(null);
LField.setText(null);
IField.setText(null);
}
// ends GUI and exits program
public void end()
{
System.exit(0);
}

public class PieChart extends JComponent {

// Class to hold a value for a slice
class PieSlice
{
//private variables
double value;
Color color;

public PieSlice(double value, Color color)
{
this.value = value;
this.color = color;
}//end Constructor

} //end class PieSlice


//private variable slices are array of PieSlice
PieSlice[] slices = new PieSlice[2];

//constructor
PieChart(double C, double H)
{
slices[0] = new PieSlice(C, Color.red);
slices[1] = new PieSlice(H, Color.blue);
setVisible(true);
}

// This method is called whenever the contents needs to be painted
public void paintComponent(Graphics g) {
// Draw the pie
this.drawPie((Graphics2D)g, getBounds(), slices);
}

// slices is an array of values that represent the size of each slice.
public void drawPie(Graphics2D g, Rectangle area, PieSlice[] slices)
{
// Get total value of all slices
double total = 0.0;
for (int p=0; p<slices.length; p++){
total += slices[p].value;
}


// Draw each pie slice
double curValue = 0.0;
int startAngle = 0;
for (int p=0; p<slices.length; p++){


// Compute the start and stop angles
startAngle = (int)(curValue * 360 / total);
int arcAngle = (int)(slices[p].value * 360 / total);

// Ensure that rounding errors do not leave a gap between the first and last slice
if (p == slices.length-1) {
arcAngle = 360 - startAngle;
} //end if

// Set the color and draw a filled arc
g.setColor(slices[p].color);
g.fillArc(area.x, area.y, 200, 200, startAngle, arcAngle);
RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHints(renderHints);
//int border=10;


//g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);


} //end for
}//end drawPie

public void resetPieChart(double capital, double interest)
{
slices[0] = new PieSlice(capital, Color.red);
slices[1] = new PieSlice(interest, Color.blue);
this.repaint();
}

}


}



Edited by macosxnerd101: Welcome to DIC! :) Please, :code:. Also, please post your properly indented code, as it is hard to follow your code unindented.

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 05 August 2010 - 05:44 PM

What part of your program are you having difficulty with? Like what lines of code?

Drawing a pie chart requires:
- determine the percentage of each part out of 100
- divide your circle into those ratios
- use the fillArc method in the Graphics/2D class to draw your portions of the pie..yum!
Was This Post Helpful? 0
  • +
  • -

#3 Guest_Oshi*


Reputation:

Re: Java Pie Chart

Posted 05 August 2010 - 06:28 PM

Hello bcranger,

The pie graph appears but does not display the "slices". I need it to display "slices" of the interest and balance of the loan.
Was This Post Helpful? 0

#4 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,479
  • Joined: 27-December 08

Re: Java Pie Chart

Posted 05 August 2010 - 06:31 PM

In that case, you can use some well-placed drawLine() invocations from your Graphics object based on percentages of the money, knowing that a circle is 360 degrees. :)
Was This Post Helpful? 0
  • +
  • -

#5 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 05 August 2010 - 07:11 PM

Or you can use fillArc and change the color for each slice..
Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,479
  • Joined: 27-December 08

Re: Java Pie Chart

Posted 06 August 2010 - 06:01 AM

It looks like that's what he's doing here:
g.setColor(slices[p].color);
g.fillArc(area.x, area.y, 200, 200, startAngle, arcAngle);
RenderingHints renderHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHints(renderHints);



Not that I can tell if the colors are different for each slice. :)
Was This Post Helpful? 0
  • +
  • -

#7 Guest_oshi*


Reputation:

Re: Java Pie Chart

Posted 06 August 2010 - 03:21 PM

I still can't figure why it is not drawing the "slices". Like you mentioned, do you think the drawLine() invocations from the Graphics object will work? If so, could you give an example of how to do it? Not my code but an example of how you would go about it. Thank you
Was This Post Helpful? 0

#8 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,479
  • Joined: 27-December 08

Re: Java Pie Chart

Posted 06 August 2010 - 04:26 PM

It wouldn't be sufficient for the color change if fillArc() isn't working. But, more or less, we start off with a circle of radius r. Now our first slice is at 0 degrees. Now if our slice takes up 25% of the pie, we know that .25(360) = 90. So we would draw a line from the center out a distance of r to the 0 degree mark, and up r to the 90 degree mark. As an example with a circle of radius 50px, and a center at (200,200):

g.drawLine(200,200,250,200); //out to the 0 degree mark
g.drawLine(200,200,200,150); //up to the 90 degree mark



For reference, here is a polar coordinate graph which describes circles of varying radii and the angles. Sort of like an expanded unit circle.

Posted Image
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1