2009-09-16 65 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(..)未被調用。

相關問題