简体   繁体   中英

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"

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

your object not initialized..

try

frame = new MainFrame();

frame.hideComponents();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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