2013-05-31 16 views
1

我有jdialog。並且我在jdialog的jpanel中添加了50個按鈕。 現在,我想這是由button.setText() 現在我的代碼看起來像這樣如何檢索java中面板組件的值

Component[] all_comp=mydialog.getComponents(); 
for(int i=0;i<=all_comp.length;i++) 
     { 
Container ct=all_comp[i].getParent(); 
String panel_name=ct.getName(); 
     } 

我盡力找出喜歡拍照的所有其他職能的所有可能的方法設置按鈕的值組件類。 但沒有結果。 現在我想獲得按鈕的值(如button.getText)。 該怎麼做?

+0

JButtons不是直接的孩子。你需要遞歸地看更深。 –

+0

該怎麼做? –

回答

1

你真正想要做的是將mydialog傳入一個方法,該方法將查找其中包含的所有JButton。這裏是哪裏,如果你在一個ContainerJDialogContainer)和List通過它將填補List所有的JButtonsJDialog包含不管你如何添加JButtons的方法。

private void getJButtons(Container container, List<JButton> buttons) { 
    if (container instanceof JButton) { 
    buttons.add((JButton) container); 
    } else { 
    for (Component component: container.getComponents()) { 
     if (component instanceof Container) { 
     getJButtons((Container) component, buttons); 
     } 
    } 
    } 
} 

基本上這個方法看起來,看看如果傳入的ContainerJButton。如果是,則將其添加到List。如果不是,則它查看Container的所有孩子,並遞歸地調用getJButtons與容器。這將搜索整個UI組件樹,並填入List及其找到的所有JButtons

這是一種醜陋必須創建一個List並把它傳遞到getButtons方法,所以我們將創建一個看起來包裝方法更好

public List<JButton> getJButtons(Container container) { 
    List<JButton> buttons = new ArrayList<JButton>(); 
    getJButtons(container, buttons); 
    return buttons; 
} 

這個便利方法簡單地爲您創建List,通過它以我們的遞歸方法,然後返回List

既然我們有遞歸方法和便捷方法,我們可以調用便捷方法來獲取我們所有的JButton s的列表。我們剛剛循環遍歷列表中的項目,並調用getText()或任何其他後你想與你的按鈕做:

for (JButton button: getJButtons(mydialog)) { 
    String text = button.getText(); 
    ... 
} 
+0

不能得到它PLZ解釋或任何其他解決方案嗎? –

+0

更新瞭解釋。 – rancidfishbreath

1

你必須檢查當前的組件是否是一個按鈕。如果是這樣,將它投到按鈕,並調用它getText()

Component[] all_comp=mydialog.getComponents(); 
for(int i=0;i<=all_comp.length;i++) { 
    if (all_comp[i] instanceof Button) { 
     String text = ((Button)all_comp[i]).getText(); 
     // this is the text. Do what you want with it.... 
    } 
} 
+0

它不工作,因爲getText不是一個組件類的方法,這就是爲什麼顯示錯誤 –