Domanda

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?

È stato utile?

Soluzione

  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.

Altri suggerimenti

you can try with this code.

frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); //here other actions
} } );

where frame is the object of your JFrame

You can also use a HierarchyListener:

//@see javax/swing/plaf/basic/BasicProgressBarUI.java
class Handler implements ChangeListener, PropertyChangeListener, HierarchyListener {
    // we don't want the animation to keep running if we're not displayable
    @Override public void hierarchyChanged(HierarchyEvent he) {
        if ((he.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0) {
            if (progressBar.isIndeterminate()) {
                if (progressBar.isDisplayable()) {
                    startAnimationTimer();
                } else {
                    stopAnimationTimer();
                }
            }
        }
    }
    //...
}

If your component needs to react to some kind of event it must implement some kind of listener - so why not make your component implement WindowListener and register it with the owner JFrame?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top