Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pie Chart

Status
Not open for further replies.

Gaz1634

Technical User
Oct 8, 2002
22
GB
Could someone tell me how to create a pie chart for a swing application, the pie chart I require must show 4 segments.

Any help is appreciated

Many Thanks, Gaz
 
Use one of the following :
Code:
java.awt.geom.Arc2D.Double
java.awt.geom.Arc2D.Float
This is rather criptic, but now you know where to look.
 
Thanks for the pointer hologram

Have you got more of an idea what I need to do, it is just that my maths is not 100% and at the moment I have not a clue where to start.
 
Another possibility :
Code:
import java.awt.*;
import java.util.*;
import javax.swing.*;

public class PieChart extends JPanel {

  float pixelWidth = 400f;
  float pixelHeight = 400f;
  float margin = 20f;
  float pieHeight = pixelHeight - (2 * margin);
  float pieWidth = pixelWidth - (2 * margin);
  private Color[] colors;
  private float[] values;
  float totalValue = 0f;

  public PieChart(Color[] colors, float[] values) {
    this.colors = colors;
    this.values = values;
    setSize((int)pixelWidth,(int)pixelHeight);
    for (int i=0; i<values.length; i++)
      totalValue += values[i];
  }

  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    float startAngle = 0f;
    float arcAngle;
    for (int i=0; i<values.length; i++) {
      arcAngle = 360f * (values[i] / totalValue);
      g2.setColor(colors[i]);
      if(i == 0) {
              g2.fillArc((int)margin,(int)margin,
                              (int)pieWidth,(int)pieHeight,
                              (int)startAngle - 5,(int)arcAngle + 5);
      } else {
              g2.fillArc((int)margin,(int)margin,
                              (int)pieWidth,(int)pieHeight,
                              (int)startAngle,(int)arcAngle);
      }
      startAngle += arcAngle;
    }
  }

}
==================================
To be called like :
Code:
import java.awt.*;
import javax.swing.*;
import java.util.Vector;

public class PieChartMain {

  private Color[] colors = { Color.blue, Color.green, Color.yellow, Color.cyan };
  private float[] values = { 70.0f, 50.0f, 20.0f, 30.0f };

  public PieChartMain() {
  }

  public static void main(String[] args) {
    PieChartMain pieChartMain = new PieChartMain();
    pieChartMain.doIt();
  }

  public void doIt() {
    JFrame f = new JFrame(&quot;PieChartExample&quot;);
    PieChart pc = new PieChart(colors, values);
    f.setSize(500,500);
    f.getContentPane().add(pc);
    f.setVisible(true);
  }

}
 
Thanks hologram, I think that is spot on what I was looking for.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top