1

我在此语句的主要方法中显示错误://非静态变量 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);

        }
 }
4

3 回答 3

3

main您试图从静态方法实例化一个PieChart非静态的内部类——将其声明为静态的。

public static class PieChart extends JComponent { 

如果你要保持PieChart非静态,那么你需要一个实例IAPieChart来创建一个实例PieChart,而你没有一个IAPieChartin实例main

于 2013-04-12T23:48:51.923 回答
0

由于您在 PieChart 类中创建了 IaPieChart,因此您的代码应该类似于:

public class PieChart extend JComponent
{

    static class IaPieChart(..)
    {
    }
}

那就是您的 IaPieChart 类实际上是 PieChart 类的辅助类,因此它应该在该类中定义,而不是相反。

此外,自定义绘画是通过覆盖该paintComponent()方法而不是 paint() 方法来完成的。

于 2013-04-12T23:48:52.273 回答
0

正如几个小时前讨论的那样,您无法从静态成员访问非静态内容。-

“不能从静态上下文引用非静态方法” JPA Java

于 2013-04-12T23:48:56.453 回答