简体   繁体   中英

How to access components in a JFrame from an Internal frame

I've created java Swing app where it consist of a jDesktoppane, inside it I'm loading/calling some jinternal frames from toggle buttons in the main frame (JFrame). And I've used jButton group to all the toggle buttons so only one frame will when a button is pressed.

Since I've used toggle button, even though I dispose a JInternalFrame the relevant toggle button will be in pressed mode (Selected). I've tried many ways and couldn't change the toggle-button's state from selected to UnSelected.

first i've created a method inside my Main JFrame.

public void buttongroup_off(){           
    buttonGroup 1.setSelected(null,false);             
}

Then I created an object inside the exit button of the JInternalFrame and through that I called the buttongroup_off() method.

private void jButton 7 ActionPerformed(java.awt.event.ActionEvent evt) {         
    Main m1= new Main();                         
    m1.buttongroup_off();                     
    this.dispose();                       
} 

but it does not work!!, Can someone help me on this? im kind a new to programming.

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {         
    Main m1= new Main();                         
    m1.buttongroup_off();                     
    this.dispose();                       
} 

In this code you are creating a new JFrame Main (which is invisible after creation) and disable its buttongroup. That is not what you want. You have to call buttongroup_off method using a reference to an existing Main instance. You may pass the reference via custom constructor for custom class that extends JInternalFrame, or you may add a static method to the Main class that will return reference to the Main instance. Like this:

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {         
    Main m1 = Main.getInstance();                         
    m1.buttongroup_off();                     
    this.dispose();                       
} 

You may also look at this question answers: managing parent frame from child frame on java swing

You can get the JFrame by using code like:

Component source = (Component)event.getSource();
Main frame = (Main)SwingUtilities.windowForComponent( source );

Now that you have a reference to the frame you can invoke any method from your custom frame class.

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