Search code examples
javaswingjframejwindow

How to get the parent container of a JWindow in Swing?


I have one JFrame and calling a JDialog from that frame while initializing. In the dialog have a JButton, when clicking on the button a new JWindow opens.

Can I fix the position of window in the main frame? How to access the parent container (JFrame extended) from JWindow extended class?


Solution

  • Use SwingUtilities.getWindowAncestor, if inside the JWindow class, refer it as this, if no, simply put object inside:

    JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
    
    JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(myJWindow);