假设我们有以下Swing应用程序:
final JFrame frame = new JFrame();
final JPanel outer = new JPanel();
frame.add(outer);
JComponent inner = new SomeSpecialComponent();
outer.add(inner);
Run Code Online (Sandbox Code Playgroud)
因此,在此示例中,我们只在框架中有一个外部面板,在面板中有一个特殊组件.隐藏和显示此特殊组件时必须执行某些操作.但问题是setVisible()在外部面板上调用而不是在特殊组件上调用.所以我不能覆盖特殊组件中的setVisible方法,我也不能在其上使用组件监听器.我可以在父组件上注册监听器但是如果外部面板也在另一个面板中并且这个外部外部面板被隐藏了怎么办?
有没有比向所有父组件递归添加组件侦听器以检测SomeSpecialComponent中的可见性更改更简单的解决方案?
coo*_*sed 24
感谢aioobe的回答 - 我通过谷歌来到这里,寻找同样的事情.:-)值得注意的是,Component.isShowing()与你的工作相同amIVisible(),所以修改后的代码片段(包括对其性质的检查HierarchyEvent)可能是:
class SomeSpecialComponent extends JComponent implements HierarchyListener {
public void addNotify() {
super.addNotify();
addHierarchyListener(this);
}
public void removeNotify() {
removeHierarchyListener(this);
super.removeNotify();
}
public void hierarchyChanged(HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0)
System.out.println("Am I visible? " + isShowing());
}
}
Run Code Online (Sandbox Code Playgroud)
aio*_*obe 14
要监听层次结构中发生的此类事件,您可以执行以下操作.
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());
}
}
Run Code Online (Sandbox Code Playgroud)
您甚至可以更精确地处理HierarchyEvents.看一下
http://java.sun.com/javase/6/docs/api/java/awt/event/HierarchyEvent.html