Detect if Java Swing component has been hidden

后端 未结 3 760
离开以前
离开以前 2021-02-05 07:49

Assume we have the following Swing application:

    final JFrame frame = new JFrame();

    final JPanel outer = new JPanel();
    frame.add(outer);

    JCompon         


        
3条回答
  •  生来不讨喜
    2021-02-05 08:18

    To listen for this kind of events occuring in the hierarchy, you could do the following.

    class SomeSpecialComponent extends JComponent implements HierarchyListener {
    
        private boolean amIVisible() {
            Container c = getParent();
            while (c != null)
                if (!c.isVisible())
                    return false;
                else
                    c = c.getParent();
            return true;
        }
    
        public void addNotify() {
            super.addNotify();
            addHierarchyListener(this);
        }
    
        public void removeNotify() {
            removeHierarchyListener(this);
            super.removeNotify();
        }
    
        public void hierarchyChanged(HierarchyEvent e) {
            System.out.println("Am I visible? " + amIVisible());
        }
    
    }
    

    You could even be more precise in the treatement of HierarchyEvents. Have a look at

    http://java.sun.com/javase/6/docs/api/java/awt/event/HierarchyEvent.html

提交回复
热议问题