Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
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;
}
}
}
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("PieChartExample");
PieChart pc = new PieChart(colors, values);
f.setSize(500,500);
f.getContentPane().add(pc);
f.setVisible(true);
}
}