我已经成功构建了一个 JComponent 饼图,它位于它自己的单独类 IAPieChart.java 中。PieChart 逻辑位于扩展 JComponent 的静态内部类中。JApplet 本身构建良好并显示“我在这里!” 表示面板是使用以下代码构建和添加的:
public class IAPieChartApplet extends JApplet {
JPanel controls;
JPanel chartPanel;
JComponent pieChart;
/**
* Initialization method that will be called after the Applet is loaded into
* the browser.
*/
public void init() {
// Build the Pie Chart Panel
buildPieChartPanel();
// Build the controls panel
buildControlsPanel();
//Set the Layout
setLayout(new FlowLayout());
//getContentPane().add(new PieChart(), controls);
//add(chartPanel);
//add(controls);
}
private void buildPieChartPanel(){
// Build the panel JPanel
chartPanel = new JPanel();
pieChart = new PieChart();
JLabel label = new JLabel("Here I Am!");
chartPanel.add(pieChart);
chartPanel.add(label);
}
private void buildControlsPanel() {
controls = new JPanel();
JLabel here = new JLabel("Here I Am");
controls.add(here);
}
}
当我运行这个 IAPieChartApplet.java 文件时,我得到了标签但没有 PieChart。
我在这里设置了一个方法断点,并进入了静态 PieChart 类:
private void buildPieChartPanel(){
// Build the panel JPanel
chartPanel = new JPanel();
pieChart = new PieChart();
JLabel label = new JLabel("Here I Am!");
chartPanel.add(pieChart);
chartPanel.add(label);
}
调试带我到这里,然后退出课堂。它确实逐步完成了 PieChart 类中的其余逻辑。这是 PieChart 静态类的代码,它再次运行良好。调试将带我到 IAPieChart 数组,然后退出该方法。这“可能”是它不显示的原因。
这是饼图类代码:
public static class PieChart extends JComponent {
IAPieChart[] pieValue = {new IAPieChart(2, Color.green),
new IAPieChart(4, Color.orange),
new IAPieChart(4, Color.blue),
new IAPieChart(3, Color.red)
};
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
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;
}
// DONT NEED endPoint to make the pieChart (Mishadoff's sample).
// needs double endPoint = 0.0D for (phcoding's sample).
double endPoint = 0.0D;
int arcStart = 0;
for (int i = 0; i < pieValue.length; i++){
/////////THIS IS THE OLD STATEMENT////////
//endPoint += (int) (endPoint * 360 / sum);
arcStart = (int) (endPoint * 360 / sum);
// this statement makes the pieChart.
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);
g.fillArc(area.x, area.y, area.width, area.height, arcStart , radius);
///////THIS IS THE OLD STATEMENT////
//arcStart += pieValue[i].arcValue;
endPoint += pieValue[i].arcValue;
// this statement will make the pieChart.
//arcStart += radius;
}
}
} // END PieChart class.*
我尝试过使用 getContentPane()、repaint() 和其他在我的搜索中看起来不错的东西,但我没有选择。在过去的几周里,我一直做得很好,但是这项任务一直困扰着我。我希望你能帮忙。