The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
December 2001



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Pie Chart

Posted by Matt Gerrans on December 13, 2001 at 3:12 PM

> OK, I'm a newbie, but I said I'd do a pie chart program for a friend, whereby the user can enter in 4 values into some text boxes and the program would calculate the percentages and display a pie chart, where each segment of the pie is a different colour. I've found some applets on the web but I need to know how it's done myself, out of curiosity. So can anyone here please help me?

It is actually quite easy. Create your pie chart class, which extends JPanel and in paintComponent(), use the fillArc() method of the Graphics object. Use setColor() to get different colored slices of pie.

Here is the paintComponent() method from a ProgressPie (shows progress as a pie instead of a bar) class I wrote (well, actually it is in progress, as I'd like to add more nifty features to it):

public void paintComponent(Graphics g)

// border is the amount of spacing from the border.
int x = border,
y = border,
w = diameter,
h = diameter;

// Normalize value to an angle is in the range 0 to 360 degrees:
int angle = (360 * (value-min))/(max - min);
int percent = (100 * (value-min))/(max - min);

g.fillArc( x, y, w, h, startAngle, -angle );

String text = (new Integer(percent)).toString() + "%";
g.setFont( new Font( "TimesRoman", Font.BOLD, 24) );
FontMetrics fontMetrix = g.getFontMetrics();
int textWidth = fontMetrix.stringWidth( text );
int textHeight = fontMetrix.getHeight();
g.setColor( textColor );
g.drawString(text, (extent.width-textWidth)/2, (extent.height+textHeight/2)/2 );

g.draw3DRect( x-border, y-border, w+2*border, h+2*border, false );

Also remember to override getPreferredSize(), or your component will not show up in most layouts!

  • RE: Pie Chart Liquid December 14, 2001 at 4:05 AM (1)
    • pie Tom December 16, 2001 at 7:44 AM (0)

Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us