如何为内容窗格创建静态引用?

How to make a static reference for a content pane?

我无法将 ContentPane 设置为静态,但我必须在另一个 class 中访问的另一种方法中访问它,但我不断收到此错误:

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();
    }
}

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

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。阅读此 post 了解更多信息 - Extends JFrame vs. creating it inside the program