2009-12-20 32 views
4

如何從CardLayout刪除JPanel(或任何其他JComponent)? 我沒有直接訪問我想要刪除的組件,但是我有索引(當我們調用cardLayout.show(parentComponent, index);時用來顯示面板的索引)。從CardLayout刪除JComponent

回答

4

當你說索引時,你的意思是插入組件時的名稱(String),對吧? 我不知道任何優雅的方式來做到這一點,但您可以嘗試獲取此容器(parentComponent)中的所有組件,並嘗試找到與您的索引具有相同名稱的組件。例如:

Component[] components = parentComponent.getComponents(); 

for(int i = 0; i < components.length; i++) { 
    if(components[i].getName().equals(index)) { 
     cardLayout.removeLayoutComponent(components[i]); 
    } 
} 
+0

是按索引我的意思是將組件添加到cardlayout時使用的字符串。感謝您的解決方案,我試了一下,它的工作。 –

+3

不應該是'if(components [i] .getName()...'看起來像'[i]'從原始代碼中缺失... –