简体   繁体   中英

Get which Jframe opened another Jframe

Say I have a JFrame called childJframe .

If I create a new childJFrame from two different JFrame s. How can I get which particular JFrame created the childJFrame.

Thus:

public class myPage1 extends javax.swing.JFrame{
    // on a Button clicked
    childJFrame cjf = new childJFrame();
    cjf.setVisible(true);
}

And the Second class is

public class myPage2 extends javax.swing.JFrame{
    // on a Button clicked
    childJFrame cjf = new childJFrame();
    cjf.setVisible(true);
}

How can I find out if cjf is an instance of myPage1 or myPage2 ?

The Window class, which JFrame descends from, has a getOwner() method that will return the "owner" Window for any child windows.

But having said that, child windows should be JDialogs, not JFrames as your application should have one and only one JFrame, and I believe that JFrames don't have owners, so that this method may return null. If you need to change "views" within the JFrame, use a CardLayout, and if you need to display child windows, use dialog windows such as JDialogs and JOptionPanes. Please read: The Use of Multiple JFrames, Good/Bad Practice? , for more on this.

But having said this, I do have to wonder if your question may in fact be an XY Problem where you ask "how do I fix this code" when the real solution is to use a different (read -- more "object oriented") approach entirely.

If your child windows must really be JFrame instances (I suppose ChildJFrame extends JFrame ), I think the simplest solution consists in keeping track of the parent JFrame in the ChildJFrame instance. Since ChildJFrame is a custom class of yours, this is easy:

  • Add a JFrame (or Frame or Window ) attribute to your ChildJFrame class;
  • Add to ChildJFrame a constructor that takes a parameter that will be assigned to the above attribute;
  • When you create a ChildJFrame instance from one of your JFrame -derived classes, just add this as a parameter.

Then you have everything you need to interact with the parent JFrame .

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