我有饼图来显示一年中的销售率,现在我想分别在每个弧的中心绘制一个字符串,以在饼图中指定月份 这就是我的代码的样子
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class TopSectionPanel extends JPanel {
double[] sales = {4000, 3000, 2000, 6000 , 10000 , 2500,
3400 , 8700 , 6734 , 1200 , 4500 , 6700};
double[] angle = new double[sales.length];
Color[] color = {Color.RED, Color.BLACK, Color.BLUE, Color.DARK_GRAY, Color.GREEN,
Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.WHITE,
Color.YELLOW, Color.GRAY};
double sum = 0;
/**
* Create the panel.
*/
public TopSectionPanel() {
setBackground(Color.CYAN);
setPreferredSize(new Dimension(400 , 400));
for(int l = 0 ; l < sales.length ; l++)
sum += sales[l];
for(int i = 0 ; i < angle.length ; i++)
angle[i] = sales[i] / sum * 360;
}
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
int radius;
// calculations to fit the circle in exact center
if(getHeight() < getWidth())
radius = (int) ((getHeight() / 2.) * 0.8) ;
else
radius = (int) ((getWidth() / 2.) * 0.8) ;
int diameter = radius * 2;
int x = (int)(getWidth() / 2) - radius;
int y = (int)(getHeight() / 2) - radius;
double a = 0;
for( int i = 0 ; i < angle.length ; i++ ) {
g.setColor(color[i]);
g.fillArc(x, y, diameter, diameter, (int)a, (int)angle[i]);
a = a + angle[i];
}
}
}
答案 0 :(得分:1)
不知道要求的细微细节,例如与弧或字体或大小的距离,我只能使用一些基本几何体生成原始草图。在循环绘制饼图后添加此项。
int mx = x + radius;
int my = y + radius;
double b = 0;
int rad = (int)(radius*1.20);
for( int i = 0 ; i < angle.length ; i++ ) {
b += angle[i]/2;
double brad = b*Math.PI/180.0;
int ix = (int)(rad*Math.cos(brad));
int iy = (int)(rad*Math.sin(brad));
g.drawString( Integer.toString(i+1), mx+ix, my-iy );
b += angle[i]/2;
}
请注意,计算出的坐标是文本开始的基线上的点。如果你真的想要围绕这一点居中文本,你将不得不计算文本的边界框,并在x和y方向上修改这些小量的坐标。