A Neat Java WindowAdaptor Trick

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);
        }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s