简体   繁体   English

如何从另一个类调用JFrame?

[英]How to call the JFrame from another class?

I have a class that creates a frame. 我有一个创建框架的课程。

public class GameDisplay{

....

public void createDisplay(){
    frame=new JFrame(title);
    canvas=new Canvas();
    canvas.setPreferredSize(new Dimension(width,height));
    canvas.setFocusable(false);
    frame.setSize(width,height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setResizable(false);
    frame.add(canvas);
    frame.pack();
}
public Canvas getCanvas(){
    return this.canvas;
}

public JFrame getFrame(){
    return frame;
}

If I have another class that would add Panels and Buttons to the frame, how can I add them? 如果我还有另一个类可以将面板和按钮添加到框架中,该如何添加它们? I have tried: 我努力了:

GameDisplay g;
Container c;
c = g.getFrame().getContentPane();

But it returns NullPointer Error. 但它返回NullPointer错误。 Thus, I can't seem to add panels to it. 因此,我似乎无法为其添加面板。

Attach your JFrame made in createDisplay() to a static variable. 将在createDisplay()中创建的JFrame附加到静态变量。 Then access that static variable from another class. 然后从另一个类访问该静态变量。

Like this 像这样

public static JFrame frame1;

Then in createDisplay() 然后在createDisplay()中

GameDisplay.frame1 = frame;

In another class to get the content pane just do 在另一个类中获取内容窗格即可

c = GameDisplay.frame1.getContentPane();

Hope this helped! 希望这对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM