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

时间:2015-03-11 04:13:41

标签: java swing static contentpane

我无法使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

我很困惑。你能帮我吗?

EDIT1

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

1 个答案:

答案 0 :(得分: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。阅读这篇文章了解更多信息 - Extends JFrame vs. creating it inside the program