首页 > cannot be referenced from a static context

cannot be referenced from a static context

package CH7;

import javax.swing.*;

public class SimpleFrameTest
{
    public static void main(String[] args)
    {
        SimpleFrame simpleFrame = new SimpleFrame();
        simpleFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        simpleFrame.setLocationByPlatform(true);
        simpleFrame.setVisible(true);
        simpleFrame.setResizable(true);
        simpleFrame.setTitle("Hello World");
    }

    private class SimpleFrame extends JFrame
    {
        public SimpleFrame()
        {
            setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        }

        public static final int DEFAULT_WIDTH = 300;
        public static final int DEFAULT_HEIGHT = 200;
    }
}

提示错误:
Error:(9, 35) java: non-static variable this cannot be referenced from a static context

不太理解这个错误,求指点。


SimpleFrame是一个非静态的内部类,只能被这个类的非静态方法访问。main方法是静态方法,使用该类创建对象时会出错。解决办法有两个:
1. 将SimpleFrame变为静态的内部类,即加上static;
2. 将类移到外面定义。

【热门文章】
【热门文章】