开发者

Is there any way to get a reference to the current frame in Java?

开发者 https://www.devze.com 2023-02-07 20:02 出处:网络
I have a menu bar class (MenuBarGUI) that I have put in all of my other classes and I need to know if I can close the current JFrame that it is contained in through an option in the menu. Normally I c

I have a menu bar class (MenuBarGUI) that I have put in all of my other classes and I need to know if I can close the current JFrame that it is contained in through an option in the menu. Normally I could call setVisible(false) then dispose() but b开发者_如何学运维ecause the menu bar doesn't have a reference to the current frame, I can't do that. Is there any way to do this?


if your MenuBarGUI class extends JMenuBar, you can use getTopLevelAncestor method to get menu bar's window.


getParent() will get the parent container. With this method you will have to do some casting. A more ideal option would be to have the menu bar could take an interface that includes a close method.

Here is an example:

   JFrame frame = new JFrame();
   JMenuBar bar = new JMenuBar();
   frame.setJMenuBar(bar);
   if(bar.getParent().getParent().getParent() instanceof JFrame){
       System.out.println(bar.getParent().getParent().getParent());
   }


None of the above approaches worked for me.

Since I only need the immediate parent of a panel, accessed them directly through a super call: super.setTitle("The new Frame Title"), etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号