2009-09-16 64 views
3

为什么这段代码从不打印“Hello2”?为什么/何时调用ComponentListener.componentShown()?

public class Test4 { 

    public static void main(String[] args) { 
     JFrame f = new JFrame(); 
     JPanel p = new JPanel(); 
     f.getContentPane().add(p); 

     JLabel x = new JLabel("Hello"); 
     p.add(x); 

     p.addComponentListener(new ComponentListener() { 

      public void componentResized(ComponentEvent arg0) { 
       System.err.println("Hello1"); 
      } 

      public void componentMoved(ComponentEvent arg0) { 
      } 

      public void componentShown(ComponentEvent arg0) { 
       System.err.println("Hello2"); 
      } 

      public void componentHidden(ComponentEvent arg0) { 
      } 
     }); 

     f.setVisible(true); 
     f.pack(); 
    } 
} 

回答

3

我猜测它是在实际对象的可见性状态发生变化时调用的。 在这种情况下,您更改了框架的可见性,而不是面板的可见性。 (默认情况下,帧开始隐藏,但面板可见) 尝试将侦听器添加到帧。

+0

是的,这是正确的,我重新阅读api文档。谢谢。 – PeterMmm 2009-09-16 15:18:05

0

Java Tutorials

组件隐藏和 所示组件的事件发生时调用一个组件的 调用setVisible方法仅作为 结果。例如, 窗口可能不具有 部件隐藏事件被解雇被小型化到 图标(图标化)。

2

的AWT的定义“可见”可能有点反直觉。从类java.awt.Component#ISVISIBLE的Javadoc中:

"Components are initially visible, with the exception of top level components such as 
Frame objects." 

根据这一描述,pis already visible before you add the ComponentListener. In fact, you can verify this if you insert a

System.out.println(p.getVisible()); 

anywhere before you call f.setVisible(true)。从这个意义上讲,当显示框架时不会改变可见性,因此componentShown(..)未被调用。

相关问题