my dog learned polymorphism*
The moose likes Swing / AWT / SWT and the fly likes I want to insert Data into the pie chart.I have put the code to gernate the Pie Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "I want to insert Data into the pie chart.I have put the code to gernate the Pie" Watch "I want to insert Data into the pie chart.I have put the code to gernate the Pie" New topic

I want to insert Data into the pie chart.I have put the code to gernate the Pie

rinku singh

Joined: Apr 22, 2003
Posts: 7
i have a program i want to show data in each pie for which that that pie is constructed.
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;

import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class Charts2D extends JFrame

public Charts2D() {
super("2D Charts");
setSize(720, 280);
getContentPane().setLayout(new GridLayout(1, 3, 10, 0));
//int nData = 10;
int[] nData = {102,87,18,95 };
int[] xData = nData;//new int[nData];
int[] yData = nData;//new int[nData];
for (int k=0; k<nData.length; k++) {
xData[k] = k;
yData[k] = (int)(Math.random()*100);

if (k > 0)
yData[k] = (yData[k-1] + yData[k])/2;

System.out.println("####### nData "+nData+" xData "+xData+" yData "+yData);
System.out.println("Math.random()*100) "+(int)(Math.random()*100));

JChart2D chart = new JChart2D(JChart2D.CHART_PIE, nData, xData,yData, "Pie Chart");
ImageIcon icon = new ImageIcon("hubble.gif");

WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {

public static void main(String argv[]) {
new Charts2D();

class JChart2D extends JPanel
int[] nData, percents;
int dataTotal;
final int PAD = 25, R_PAD = 5;
public static final int CHART_LINE = 0;
public static final int CHART_COLUMN = 1;
public static final int CHART_PIE = 2;
public static final int EFFECT_PLAIN = 0;
public static final int EFFECT_GRADIENT = 2;
public static final int EFFECT_IMAGE = 3;
protected int m_chartType = CHART_LINE;
protected JLabel m_title;
protected ChartPanel m_chart;
protected int[] m_nData;
protected int[] m_xData;
protected int[] m_yData;
protected int m_xMin;
protected int m_xMax;
protected int m_yMin;
protected int m_yMax;
protected double[] m_pieData;
protected int m_effectIndex = EFFECT_PLAIN;
protected Stroke m_stroke;
protected GradientPaint m_gradient;
protected Image m_foregroundImage;
protected Color m_lineColor =;
protected Color m_columnColor = Color.yellow;
protected int m_columnWidth = 15;
protected boolean m_drawShadow = false;

public JChart2D(int type, int[] nData,int[] yData, String text)
this(type, nData, null, yData, text);

public JChart2D(int type, int[] nData, int[] xData,int[] yData, String text)
super(new BorderLayout());


m_title = new JLabel(text, JLabel.CENTER);
add(m_title, BorderLayout.NORTH);

m_chartType = type;
if (xData==null)
//xData = new int[nData];
for (int k=0; k<nData.length; k++)
xData[k] = k;

if (yData == null)
throw new IllegalArgumentException("yData can't be null");
if (nData.length > yData.length)
throw new IllegalArgumentException("Insufficient yData length");
if (nData.length > xData.length)
throw new IllegalArgumentException("Insufficient xData length");

m_nData = nData;
m_xData = xData;
m_yData = yData;
m_xMin = m_xMax = 0; // To include 0 into the interval
m_yMin = m_yMax = 0;

for (int k=0; k<m_nData.length; k++)
m_xMin = Math.min(m_xMin, m_xData[k]);
m_xMax = Math.max(m_xMax, m_xData[k]);
m_yMin = Math.min(m_yMin, m_yData[k]);
m_yMax = Math.max(m_yMax, m_yData[k]);

if (m_xMin == m_xMax)

if (m_yMin == m_yMax)

if (m_chartType == CHART_PIE)
double sum = 0;
for (int k=0; k<m_nData.length; k++)
m_yData[k] = Math.max(m_yData[k], 0);
sum += m_yData[k];

m_pieData = new double[m_nData.length];

for (int k=0; k<m_nData.length; k++)
m_pieData[k] = m_yData[k]*360.0/sum;

m_chart = new ChartPanel();
add(m_chart, BorderLayout.CENTER);


public void setEffectIndex(int effectIndex) {
m_effectIndex = effectIndex;

public int getEffectIndex() { return m_effectIndex; }

public void setStroke(Stroke stroke) {
m_stroke = stroke;

public Stroke getStroke() { return m_stroke; }

public void setGradient(GradientPaint gradient) {
m_gradient = gradient;
public GradientPaint getGradient() { return m_gradient; }

class ChartPanel extends JComponent
int m_xMargin = 5;
int m_yMargin = 5;
int m_pieGap = 10;
int m_x;
int m_y;
int m_w;
int m_h;
ChartPanel() {
protected void processComponentEvent(ComponentEvent e) {
public void calcDimensions() {

Dimension d = getSize();
m_x = m_xMargin;
m_y = m_yMargin;
m_w = d.width-2*m_xMargin;
m_h = d.height-2*m_yMargin;


public void paintComponent(Graphics g) {

int width = getWidth();
int height = getHeight();
int xp,yp;
String s;
int dataWidth, dataHeight;
int cx = width/2;
int cy = height/2;

Graphics2D g2 = (Graphics2D) g;
int x0 = 0;
int y0 = 0;
Font font = new Font("lucida sans unicode", Font.PLAIN, 16);

FontRenderContext frc = g2.getFontRenderContext();

if (m_stroke != null)
GeneralPath path = new GeneralPath();

///////////////////// chart /////////////////////////
switch (m_chartType) {


double start = 0.0;
double finish = 0.0;
int ww = m_w - 2*m_pieGap;
int hh = m_h - 2*m_pieGap;

int rcolor =30;
int gcolor =20;
int bcolor =10;

for (int k=0; k<m_nData.length; k++)

finish = start+m_pieData[k];

s = String.valueOf(percents[k]) + "%";

double f1 = Math.min(90-start, 90-finish);
double f2 = Math.max(90-start, 90-finish);
System.out.println("%%%%%%%%%%%%% finish "+finish+" "+f1+" "+f2);

Shape shp = new Arc2D.Double(m_x, m_y, ww, hh,f1, f2-f1, Arc2D.PIE);

//this is where i want to show data( 102,87,18,95) in each pie. can someone write the code for this.
double f = (f1 + f2)/2*Math.PI/180;
AffineTransform s1 = AffineTransform.getTranslateInstance(m_pieGap*Math.cos(f),-m_pieGap*Math.sin(f));
g2.setColor(new Color(0, 140, 180));

s1.translate(m_pieGap, m_pieGap);
Shape piece = s1.createTransformedShape(shp);
path.append(piece, false);
start = finish;


if (m_effectIndex==EFFECT_GRADIENT && m_gradient != null)
else if (m_effectIndex==EFFECT_IMAGE &&m_foregroundImage != null)
fillByImage(g2, path, 0);
else {


protected void fillByImage(Graphics2D g2,Shape shape, int xOffset) {

if (m_foregroundImage == null)

int wImg = m_foregroundImage.getWidth(this);
int hImg = m_foregroundImage.getHeight(this);

if (wImg <=0 || hImg <= 0)
Rectangle bounds = shape.getBounds();
System.out.println("bounds "+bounds);

for (int xx = bounds.x+xOffset;xx < bounds.x+bounds.width; xx += wImg)
for (int yy = bounds.y; yy < bounds.y+bounds.height;yy += hImg)
g2.drawString("x", xx, yy);


public void prepareData()
for(int i = 0; i < nData.length; i++)
dataTotal += nData[i];
percents = new int[nData.length];
int dataPlus = 0;

for(int i = 0; i < nData.length; i++){
dataPlus += nData[i];
percents[i] = Math.round(100 * dataPlus/dataTotal);

public void enterData(int[] nData)
this.nData = nData;
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
rinku, do you have a question? Oh, now I see you've included a comment - "//this is where i want to show data( 102,87,18,95) in each pie. can someone write the code for this."

Most folks 'round these parts are more likely to help you out by nudging you in the right direction towards a solution. I'd suggest trying to work out a solution as best you can, then asking a pointed question about a specific problem you seem to be having.

When posting code, please be sure to surround the code with the [code] and [/code] UBB Tags. This will help to preserve the formatting of the code, thus making it easier to read and understand.

Note that this is the J2ME forum. Your post doesn't seem to have much to do with J2ME.

Moving this to the Swing / JFC / AWT forum...

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
Adapting your data for a pie chart is fairly easy. Add up your data values and use the total to calculate the percentage of each data item. Multiply this percentage by the total arc, 360 if you work in degrees and 2 pi if you work in radians. Draw the line at the new angle for each data item as you move around the circle.
rinku singh

Joined: Apr 22, 2003
Posts: 7
thanks Craig . I was looking how to display the value of 100,200,300,400 within the pie , pie representing each item.I am unable to caluclate the value of X,y co-ordinate where is should display the Data. IF you can explain me how to calculate the value for X,Y that will be great.If you know how to calculate can u put that piece and code and also explain how we are calcilating the valeu .

Thanks in advance.

//g2.drawString(s, xp, yp); where S is the value of the Data.
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
rinku singh

Joined: Apr 22, 2003
Posts: 7

what's the logic behind these

1)double dia = Math.min(w,h)*0.85; ( why the value 0.85 ?)
2)cx = w/2 + (dia/2) * Math.cos(theta + phi/2) * 7/12;
cy = h/2 + (dia/2) * Math.sin(theta + phi/2) * 7/12;
// text origin at lower left of box
sx = cx - textWidth/2;
sy = cy + textHeight/2;

Why the value 7/12 ?.
Can you describe this logic. how you come with this to determine the value of x,y co-ordinate to display Value. Is this some sort of standard formula to to calculate the poistion of x,y to display value in pie ?.
Craig Wood
Ranch Hand

Joined: Jan 14, 2004
Posts: 1535
The values in 1) and 2) are magic numbers.

1)double dia = Math.min(w,h)*0.85; ( why the value 0.85 ?)

The 0.85 is to provide some padding between the edge of the circle and the edge of the JPanel. It is arbitrary and I chose it for visual appeal.

2) cx = w/2 + (dia/2) * Math.cos(theta + phi/2) * 7/12;
cy = h/2 + (dia/2) * Math.sin(theta + phi/2) * 7/12;

Again this (7/12) is an arbitrary value I chose to locate the center of the text along the midline radial of each pie wedge. I chose it as a reasonable value for centering the text.

// text origin at lower left of box
sx = cx - textWidth/2;
sy = cy + textHeight/2;

These values merely center the text over the point (cx, cy).

I don't know of any standards for making charts. Everything is hand–made according to what you need or want to do.
I agree. Here's the link:
subject: I want to insert Data into the pie chart.I have put the code to gernate the Pie
Similar Threads
Can I add an arrow onto a shape in a GridLayout?
Custom Buttons
How to plot a graph in Java ?
Print Preview in Java swing
a Jbutton with a rounded border