Reputation: 35
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
?
Upvotes: 0
Views: 75
Reputation: 285415
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.
Upvotes: 7
Reputation: 1010
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:
JFrame
(or Frame
or Window
) attribute to your ChildJFrame
class;ChildJFrame
a constructor that takes a parameter that will be assigned to the above attribute;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
.
Upvotes: 3