从jframe上添加的jpanel类调用jframe中的函数

时间:2014-12-22 16:45:03

标签: java swing jpanel

我有一个名为frame的jframe,1个名为mainpanel的jpanel和另一个名为ControlPanel的jpanel。

jpanel ControlPanel已添加到jframe框架的主面板内。

private void onLoad(){
ControlPanel cpanel = new ControlPanel;
mainpanel.add(cpanel);
}

在jframe框架内,我有一个函数:

public void hideComponents(){
//code here
}

因为我已将cpanel添加到框架的主面板中,如何从cpanel中调用框架中的功能?

我所做的是在controlpanel类中声明了框架

private MainFrame frame;

然后创建了一个调用框架功能的按钮

frame.hideComponents(); // error occurs pointing here "NullPointerException"

2 个答案:

答案 0 :(得分:2)

您必须将MainFrame类实例作为参数传递给控制面板构造函数 然后从那里调用hide Components方法。示例如下:

public final class ControlPanel extends JPanel {
    // Optional: you can even declare your MainFrame as private field member
    // if you want to keep track of the frame instance. But let's assume
    // you don't need that in your occasion

    public ControlPanel(MainFrame frame) {
          frame.hideComponents();
    }
    //maybe other code 
    ...
}

示例:

private void onLoad(){
  ControlPanel cpanel = new ControlPanel(MainFrame.this);
  mainpanel.add(cpanel);
}

答案 1 :(得分:0)

您的对象未初始化..

尝试

frame = new MainFrame();

frame.hideComponents();