2014-09-19 47 views
1

這裏就是我想要做的事:如何迭代任何JComponent的組件?

public static AbstractButton findButtonInContainerByText(String text, JComponent container){ 
    for(Component component : container.getComponents()){ 
     if(!(component instanceof AbstractButton)) 
      continue; 
     AbstractButton button = (AbstractButton) component; 
     if(button.getText().equals(text)) 
      return button; 
    } 
    throw new ItemNotFoundException("There is no button with the text '" + text + "' in the container " + container + "."); 
} 

問題是,這並不JMenu s請正確工作。這是因爲由於某些原因,您不能僅僅致電getComponents()並獲得所有組件,您必須致電getMenuComponents()。顯然,我不想用這種方法對各種特殊情況進行類型檢查。

有沒有一種方法可以正確地遍歷各種JComponent內的組件?

作爲備註:您認爲您有這個API設計決定的原因嗎? JMenu#getComponents()正在欺騙,因爲這不是它所做的。是否有這個問題的原因?

+1

'JMenu'編碼方式,它是底層的'JPopupMenu',它包含組件,而不是'JMenu'本身。見[這裏的代碼](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/javax/swing/JMenu.java)。也許只是爲了確保'getComponents'返回'JComponent'的實際子代......那麼爲什麼'JPopupMenu'不存在......要愛Java。 – 2014-09-19 16:04:16

+3

看看[class hieratchy](http://docs.oracle.com/javase/7/docs/api/javax/swing/JMenu.html)。菜單和菜單項都是「JComponents」。也許你沒有錯誤地遍歷組件。 'getComponents()'只會得到直接的孩子,而不是那些孩子所包含的。你需要做一些遞歸搜索。也許你正在遍歷錯誤的組件。菜單mar包含在根窗格中,實際上位於根窗格的分層窗格中。發佈一個[MVCE](http://stackoverflow.com/help/mcve),以便我們看到你是如何做到這一點的。 – 2014-09-19 16:07:04

+0

另見[這裏](http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html) – 2014-09-19 16:08:54

回答