📄 e590. drawing a pie chart.txt
字号:
This example implements a method for drawing a pie chart.
// Class to hold a value for a slice
public class PieValue {
double value;
Color color;
public PieValue(double value, Color color) {
this.value = value;
this.color = color;
}
}
// slices is an array of values that represent the size of each slice.
public void drawPie(Graphics2D g, Rectangle area, PieValue[] slices) {
// Get total value of all slices
double total = 0.0D;
for (int i=0; i<slices.length; i++) {
total += slices[i].value;
}
// Draw each pie slice
double curValue = 0.0D;
int startAngle = 0;
for (int i=0; i<slices.length; i++) {
// Compute the start and stop angles
startAngle = (int)(curValue * 360 / total);
int arcAngle = (int)(slices[i].value * 360 / total);
// Ensure that rounding errors do not leave a gap between the first and last slice
if (i == slices.length-1) {
arcAngle = 360 - startAngle;
}
// Set the color and draw a filled arc
g.setColor(slices[i].color);
g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
curValue += slices[i].value;
}
}
Here's some code that uses the drawPie() method:
class MyComponent extends JComponent {
PieValue[] slices = new PieValue[4];
MyComponent() {
slices[0] = new PieValue(25, Color.red);
slices[1] = new PieValue(33, Color.green);
slices[2] = new PieValue(20, Color.pink);
slices[3] = new PieValue(15, Color.blue);
}
// This method is called whenever the contents needs to be painted
public void paint(Graphics g) {
// Draw the pie
drawPie((Graphics2D)g, getBounds(), slices);
}
}
// Show the component in a frame
JFrame frame = new JFrame();
frame.getContentPane().add(new MyComponent());
frame.setSize(300, 200);
frame.setVisible(true);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -