JPanel which one of Listeners is proper for visibility is changed

好久不见. 提交于 2019-11-26 14:40:31
Mikle Garin

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!