代码之家  ›  专栏  ›  技术社区  ›  PeterMmm

调用ComponentListener.ComponentShowed()的原因/时间?

  •  3
  • PeterMmm  · 技术社区  · 16 年前

    为什么这个代码从不打印“Hello2”?

    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 回复  |  直到 16 年前
        1
  •  3
  •   Omry Yadan    16 年前

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

        2
  •  3
  •   Thomas Thomas    16 年前

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

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

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

    调用f.setVisible(true)之前的任何位置。从这个意义上讲,在显示帧时可见性不会改变,因此不会调用ComponentShowed(..)。

        3
  •  0
  •   Carlos Tasada    16 年前

    从…起 Java Tutorials

    隐藏的组件和 组件显示的事件仅在以下情况下发生: setVisible方法。例如,一个 图标(图标化),不带 正在激发的组件隐藏事件。