我在此语句的主要方法中显示错误://非静态变量 this cannot be referenced from a static context
frame.getContentPane().add(new PieChart());
我认为这就像加载内容窗格并向其中添加 PieChart 类一样简单。我今天花了几个小时,希望能在这个问题上得到帮助。我有 10 周的 Java 经验,直到现在还没有超出我的深度。任何意见是极大的赞赏。
Here is my PieChart program:
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 marker; // holds value for color (expressed as an integer
public IAPieChart(double value, Color color){
this.arcValue = value;
this.marker = color;
}
public class PieChart extends JComponent {
IAPieChart[] pieValue = {new IAPieChart(5, Color.green),
new IAPieChart(33, Color.orange),
new IAPieChart(20, Color.blue),
new IAPieChart(15, Color.red)
};
public void paint(Graphics g) {
drawPie((Graphics2D) g, getBounds(), pieValue);
}
void drawPie(Graphics2D g, Rectangle area, IAPieChart[] pieValue){
double sum = 0.0D;
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].marker);
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()); // This is where the error occurs.
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}