Search code examples
javaswingjframewindowlistener

What event should I use to detect parent JFrame closing in custom JComponent?


I have a custom JComponent placed in a JFrame (Well placed in a JPanel on a JFrame). I have used setDefaultCloseOperation() to set my JFrame to DISPOSE_ON_CLOSE.

My custom component has a Timer that continues to run after the frame has been closed. I know I could add a WindowListener to the JFrame and then make a call to the custom component to stop, but I would prefer to have my component be completely encapsulated. Is there any event I can use to detect when the parent JFrame has been closed from within my JComponent?


Solution

    1. Have you class implement the windowClosing event of the WindowListener.
    2. Add an AncestorListener to your custom component and listen for the ancestorAdded event. This event is generated when you add your component to a visible GUI or when the GUI containeing your comonent is realized.
    3. In the ancestorAdded event you add your WindowListener to the frame. You can get the current frame by using the SwingUtilties.windowForComponent(...) method.

    Now all the logic is self contained in your class.