我正在制作一个包含 4 个不同元素的饼图。我可以让元素出现在 JFrame 中,但我无法完成饼图圆圈。这些是元素:
public static class PieChart extends JComponent {
IAPieChart[] pieValue = {new IAPieChart(5, Color.green),
new IAPieChart(4, Color.orange),
new IAPieChart(3, Color.blue),
new IAPieChart(2, Color.red)
};
现在元素已实例化并加载到数组中,我使用此方法绘制它们:
public void paintComponent(Graphics g) {
drawPie((Graphics2D) g, getBounds(), pieValue);
}
这种方法将元素放在 JFrame 上,但只给了我大约 120 度的圆。:
void drawPie(Graphics2D g, Rectangle area, IAPieChart[] pieValue){
double sum = 0.0;
for (int i = 0; i < pieValue.length; i++) {
sum += pieValue[i].arcValue;
}
double endPoint = 0.0D;
int arcStart = 0;
for (int i = 0; i < pieValue.length; i++){
endPoint = (int) (endPoint * 360 / sum);
int radius = (int) (pieValue[i].arcValue * 360/ sum);
g.setColor(pieValue[i].color);
g.fillArc(area.x, area.y, area.width, area.height, arcStart , radius);
radius += pieValue[i].arcValue;
}
}
}
我不知所措。我有大约 10 周的 Java 经验,所以这主要是反复试验。我正在寻找一种方法来完成这个圈子。我将值降低到可以显示所有颜色的最低点。任何更大的东西都会消除一种颜色或另一种颜色。
我希望你能帮忙。这是完整的程序 IAPieChart:
package iapiechart;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
class IAPieChart{
double arcValue; // passes a value for the calculation of the arc.
Color color; // holds value for color (expressed as an integer
public IAPieChart(double value, Color color){
this.arcValue = value;
this.color = color;
}
public static class PieChart extends JComponent {
IAPieChart[] pieValue = {new IAPieChart(5, Color.green),
new IAPieChart(4, Color.orange),
new IAPieChart(3, Color.blue),
new IAPieChart(2, Color.red)
};
public void paintComponent(Graphics g) {
drawPie((Graphics2D) g, getBounds(), pieValue);
}
void drawPie(Graphics2D g, Rectangle area, IAPieChart[] pieValue){
double sum = 0.0;
for (int i = 0; i < pieValue.length; i++) {
sum += pieValue[i].arcValue;
}
double endPoint = 0.0D;
int arcStart = 0;
for (int i = 0; i < pieValue.length; i++){
endPoint = (int) (endPoint * 360 / sum);
int radius = (int) (pieValue[i].arcValue * 360/ sum);
g.setColor(pieValue[i].color);
g.fillArc(area.x, area.y, area.width, area.height, arcStart , radius);
radius += pieValue[i].arcValue;
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new PieChart());
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}