1 Replies - 3449 Views - Last Post: 09 April 2007 - 03:19 AM Rate Topic: -----

#1 Ghost_Rider  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 16-March 07

Adding Pie Chart

Post icon  Posted 08 April 2007 - 05:48 PM

I was wondering if someone could give me some pointers on how to add a pie chart to an existing program. Everything that I've tried will not work for me. So if there is some out there that can point me in the right direction, I would appericate your help.

Is This A Good Question/Topic? 0
  • +

Replies To: Adding Pie Chart

#2 Programmist  Icon User is offline

  • Refactorer in Chief
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,843
  • Joined: 02-January 06

Re: Adding Pie Chart

Posted 09 April 2007 - 03:19 AM

I've done this before and I'll give you a "skeleton" example of how to draw something like this. You'll still have to think about the problem, but this should get you started. I extended an Arc2D.Float as a pie "slice" and a JPanel as my pie chart, which had a collection of slices. Utilize the paintComponent method of JPanel (your pie chart class) to start the drawing of you slices. Here's how I have it set up:

Here is the relevant part of the overridden paintComponent method in my PieChart object:
	public void paintComponent( Graphics g )
		super.paintComponent( g );
		Graphics2D g2d = (Graphics2D)g;

		// more code here...

		drawSlices( g2d );

The drawSlices method (still PieChart) basically iterates through the chart's collection of slices and calls the draw method of each (which takes a Graphics object as a parameter.
	private void drawSlices( Graphics2D g2d )
		for ( PieSlice slice : slices )
			slice.draw( g2d );

The draw method of the PieSlice class is as simple as could be. The Slice simply takes the passed Graphics2D object and draws itself onto it.
	public void draw( Graphics2D g2d )
		g2d.setColor( getColor() );
		g2d.fill( this );

I prefer to use Graphics2D over Graphics because it's easier to work with, in my opinion, and it allows rendering hints. I omitted the code related to that because it could have been confusing, but look it up as it will allow you to turn off and on certain features like anti-aliasing. So, to recap, PieSlice extends Arc2D.Float and PieChart extends JPanel and contains a collection of PieSlices. The paintComponent method of PieChart, which is inherited from JPanel, sets off a series of events which basically amounts to iterating through all of the PieSlices and drawing them onto its Graphics object. I'll leave it up to you to figure out the rest of it (setting the color and dimension of each slice among other things).

This post has been edited by alcdotcom: 09 April 2007 - 03:24 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1