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

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

阅读 13.5k
1 个回答

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题