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

I have a menu class (MenuBarGUI) that I placed in all my other classes, and I need to know if I can close the current JFrame, which it contains through the menu option. Normally, I could call setVisible (false), then dispose (), but since there is no link to the current frame in the menu bar, I cannot do this. Is there any way to do this?

+4
source share
3 answers

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

+4
source

getParent() will get the parent container. With this method you will need to do some kind of casting. A better option would be for the menu bar to use an interface that includes the 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()); } 
+1
source

None of the above approaches worked for me.

Since I only need the immediate parent of the panel, they are accessed through a super call: super.setTitle ("New frame name"), etc.

0
source

Source: https://habr.com/ru/post/1338013/


All Articles