I discovered this neat trick when I was trying to have a status bar get updated with an element when a Java dialog box gets created (JDialog). The element in the status bar gets removed when the dialog box is closed. This is handy, and also gives an example of the order that listeners get added with creation of Java GUI elements.
//... JDialog box initialization code ... StatusBar.addTemporaryElement(temporaryElement, this); //... Rest of JDialog initialization ...
//... in StatusBar class (extends JFrame) public void addTemporaryElement(JComponent temporaryElement, JDialog dialog) { //example, adding a temporary label or button to the status bar frame add(temporaryElement, JFrame.RIGHT_ALIGNMENT); dialog.addWindowListener(new MyWindowListener(temporaryElement)); } public class MyWindowListener extends WindowAdapter { private JComponent tmpElement; MyWindowListener(JComponent tmpElement) { this.tmpElement = tmpElement; } @Override public void windowClosed(WindowEvent e) { remove(tmpElement); } }