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
  • 197,959
  • 33
  • 457
  • 689
GregH
  • 4,772
  • 6
  • 43
  • 98

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
  • 342,548
  • 56
  • 784
  • 738
4
Window window = SwingUtilities.windowForComponent(...);
camickr
  • 316,400
  • 19
  • 155
  • 279