call function in the jframe from the jpanel class which was added on jframe

i have 1 jframe named frame, 1 jpanel within the jframe named mainpanel and 1 jpanel from another class named ControlPanel.

the jpanel ControlPanel was added inside the jframe frame's mainpanel.

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

inside the jframe frame, i have a function:

public void hideComponents(){
//code here
}

since i've added the cpanel to the frame's mainpanel, how do i call a function in the frame from within the cpanel?

what i've done is declared the frame in the controlpanel class

private MainFrame frame;

then created a button calling the frame's function

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

Upvotes: 0

Views: 2042

Answers (2)

GregoAvg
GregoAvg

Reputation: 116

you have to pass the MainFrame class instance as parameter in ControlPanel constructor an then call hideComponents method from there. Example goes here:

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 
    ...
}

Example:

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

Upvotes: 2

BDRSuite
BDRSuite

Reputation: 1612

your object not initialized..

try

frame = new MainFrame();

frame.hideComponents();

Upvotes: 0

Related Questions