2013-12-13 52 views
0

在for循環中創建它們後,如何刪除JButton對象?在for循環中創建它們後刪除JButton

我在for循環中創建了按鈕對象,之後我想將它們從 中刪除,但這有可能嗎?

我有如下算法:

For each one of the elements in the ArrayList 
    Create a JButton(text) , where text is the current value for the specific element 
    add it to the GridLayout 

的Java代碼示例:

ArrayList AL; 
for(int i = 0; i < AL.size() - 1 ; i++) { 
    JButton JB = new JButton(get(i)); //add the text in JButton 
    grid.add(JB); 
    } 

我怎樣才能事後除去它們? 因爲我在飛行中創建它們,有可能將它們刪除嗎?

回答

2

您可以稍後通過將JButton引用存儲在數組中刪除它們。只需遍歷該數組或列表並刪除條目即可。

+0

它的工作原因我創建了一個ArrayList list = new ArrayList (),我存儲了對象引用,之後我遍歷了該數組,並刪除了條目。謝謝 – programmer

2

您可以掃描您添加到的對象的子項並將其移除,也可以在創建它們時保留它們的列表,然後掃描列表以刪除它們。