要监听层次结构中发生的这种事件,您可以执行以下操作。
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());
}
}
您甚至可以在层次结构事件的处理中更精确。看一下