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
RE: Pie Chart
Posted by Liquid on December 14, 2001 at 4:05 AM
> > 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!
Thanks a lot =)
- pie Tom December 16, 2001 at 7:44 AM