import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PieChartPanel extends JPanel
{
protected int m_originX;
protected int m_originY;
protected int m_radius;
// final static private double HALF_PI = Math.PI / 2.0;
// final static private double TWO_PI = Math.PI * 2.0;
final static private double D2R = Math.PI / 180.0; // Degrees to radians.
private int m_xGap = 5;
private int m_inset = 40;
private List<Double> m_values = null;
private List<String> m_labels = null;
private List<Color> m_colors;
public PieChartPanel()
{
createDefaultColors();
}
public void createDefaultColors()
{
m_colors = new ArrayList<Color>();
m_colors.add(Color.GREEN);
m_colors.add(Color.RED);
m_colors.add(Color.YELLOW);
m_colors.add(Color.BLUE);
m_colors.add(Color.PINK);
}
public void setValues(List<Double> values)
{
m_values = values;
}
public void setLabels(List<String> labels)
{
m_labels = labels;
}
public void setColors(List<Color> colors)
{
m_colors = colors;
}
public void calcPercentagesOfValues()
{
double total = 0;
for (double value : m_values)
{
total += value;
}
for (int i=0; i<m_values.size(); i++)
{
m_values.set(i, m_values.get(i)/total);
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Dimension size = getSize();
m_originX = size.width / 2;
m_originY = size.height / 2;
int diameter = ( m_originX < m_originY ? size.width - m_inset : size.height - m_inset );
m_radius = ( diameter / 2 ) + 1;
int cornerX = ( m_originX - ( diameter / 2 ) );
int cornerY = ( m_originY - ( diameter / 2 ) );
int startAngle = 0;
int arcAngle = 0;
if (m_values!=null)
{
for (int i = 0; i < m_values.size(); i++)
{
arcAngle = (int) ( i < m_values.size() - 1 ? Math.round(m_values.get(i) * 360) : 360 - startAngle );
g.setColor(m_colors.get(i % m_colors.size()));
g.fillArc(cornerX, cornerY, diameter, diameter, startAngle, arcAngle);
if (m_labels!=null && m_labels.get(i)!=null)
{
g.setColor(Color.BLACK);
drawLabel(g, m_labels.get(i), startAngle + ( arcAngle / 2 ));
}
startAngle += arcAngle;
}
}
else
{
arcAngle = 360;
g.setColor(Color.LIGHT_GRAY);
g.fillArc(cornerX, cornerY, diameter, diameter, startAngle, arcAngle);
g.setColor(Color.BLACK);
drawLabel(g, "Keine Werte gegeben!", startAngle + ( arcAngle / 2 ));
}
g.setColor(Color.black);
g.drawOval(cornerX, cornerY, diameter, diameter); // Cap the circle.
}
public void drawLabel(Graphics g, String text, double angle)
{
// g.setFont(textFont);
// g.setColor(textColor);
double radians = angle * D2R;
int x = (int) ( ( m_radius + m_xGap ) * Math.cos(radians) );
int y = (int) ( ( m_radius + m_xGap ) * Math.sin(radians) );
if (x < 0)
{
x -= SwingUtilities.computeStringWidth(g.getFontMetrics(), text);
}
if (y < 0)
{
y -= g.getFontMetrics().getHeight();
}
g.drawString(text, x + m_originX, m_originY - y);
}
}