-1

我无法制作ContentPane静态,但我必须访问它在我在另一个类中访问的另一种方法中,我不断收到此错误:

Cannot make a static reference to the non-static method
    getContentPane() from the type JFrame

..当我尝试setSize

Cannot make a static reference to the non-static method setDefaultCloseOperation(int) from the type JFrame

我感到很困惑。你能帮我么?

编辑1

ToutrialStart

public class ToutrialStart extends JFrame implements ActionListener
{
static Container contentPane = getContentPane();
public static void schoolDecider()
{
    contentPane.setLayout(null);
    contentPane.setBackground(Color.BLACK);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(1024, 600);
    setLocation(0,0);
    setTitle("Title");
    setResizable(false);
}
}

touDia

public class touDia extends JFrame implements actionListener
{
    public void school()
    {
        ToutrialStart.schoolDecider();
    }
}
4

1 回答 1

0

您收到此错误是因为您在此处使用的 JFrame 类的所有方法都是非静态的,并且您无法对非静态方法进行静态引用。但是,您可以按如下方式重写您的代码 -

public class ToutrialStart extends JFrame implements ActionListener
{
Container contentPane = getContentPane();
public void schoolDecider()
{
    contentPane.setLayout(null);
    contentPane.setBackground(Color.BLACK);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(1024, 600);
    setLocation(0,0);
    setTitle("Title");
    setResizable(false);
}
}
public class touDia extends JFrame implements actionListener
{
    public void school()
    {
        new ToutrialStart().schoolDecider();
    }
}

此外,您应该避免扩展 JFrame。阅读这篇文章以获取更多信息 - 扩展 JFrame 与在程序中创建它

于 2015-03-11T05:51:45.237 回答