1

I have a multiple JPanels which are put in a dialogue and after many hours, I am still unable to find the frame in which the JPanels are stored in. I was wondering if there is a method which would return the JFrame (end goal is to call setDefaultCloseOperation() on the JFrame). I was thinking getParent() would do this however I am still unable to call setDefaultCloseOperation no matter how many layers of parents I go through.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
GregH
  • 5,125
  • 8
  • 55
  • 109

2 Answers2

4

There is a utility method for it: SwingUtilities.getWindowAncestor()

If you add your JPanel to a JFrame, it will be obviously a JFrame instance:

JFrame f = (JFrame) SwingUtilities.getWindowAncestor(panel);

Note: getWindowAncestor() and windowForComponent() provide the same functionality.

icza
  • 389,944
  • 63
  • 907
  • 827
4
Window window = SwingUtilities.windowForComponent(...);
camickr
  • 321,443
  • 19
  • 166
  • 288