JPanel which one of Listeners is proper for visibility is changed

If you want to listen EXACTLY the visibility changes – use ComponentListener or ComponentAdapter:

    JPanel panel = new JPanel ();
    panel.addComponentListener ( new ComponentAdapter ()
    {
        public void componentShown ( ComponentEvent e )
        {
            System.out.println ( "Component shown" );
        }

        public void componentHidden ( ComponentEvent e )
        {
            System.out.println ( "Component hidden" );
        }
    } );

But that visibility might not be the one you think about. isVisible() flag will be true even if the Component is not added to any Container and hence not showing at all!

That visibility a has a slightly different purpose. You can use it to manually hide the Component that is already added and shown somewhere in your application. In that case, (if you use setVisible(false)) it will become hidden and every ComponentListener of that Component will be informed about that change.

So, talking about actual visibility…

This is what you should use to listen to actual component appearance/disappearance:

    JPanel panel = new JPanel ();
    panel.addAncestorListener ( new AncestorListener ()
    {
        public void ancestorAdded ( AncestorEvent event )
        {
            // Component added somewhere
        }

        public void ancestorRemoved ( AncestorEvent event )
        {
            // Component removed from container
        }

        public void ancestorMoved ( AncestorEvent event )
        {
            // Component container moved
        }
    } );

I always use that listener to determine when the Component is added somewhere and also to listen when it is moved/removed.

Also, you can always check if the Component is actually visible to application user by calling isShowing() method:

boolean userCanSeeThePanel = panel.isShowing();

This will return true ONLY if that panel is added to VISIBLE to user frame and isVisible() flag is also true (it is usually true, unless you set it to false).

I guess that’s all I can tell you about visibility. I might have misunderstood your question. Correct me if I am wrong in that case.

Leave a Comment