2011-08-19 65 views
7

我在JPanel中動態添加和刪除組件。 添加和刪除功能正常工作,但是當我刪除組件時,它將刪除最後一個組件,而不是要刪除的組件。從JPanel動態刪除組件

我該如何解決這個問題?

+3

請發表您的代碼,以便我們可以提供幫助。 –

+6

爲了更好地提供幫助,請包括[SSCCE](http://www.sscce.org) – mre

+3

您是否正在使用「public void remove(int index)」而不是「public void remove(Component comp)」?如果您想要更好的答案,請發佈SSCCE。 –

回答

6

使用方法Container.remove(Component),可以從容器中刪除任何組件。例如:

JPanel j = new JPanel(); 

JButton btn1 = new JButton(); 

JButton btn2 = new JButton(); 

j.add(btn1); 

j.add(btn2); 

j.remove(btn1); 
3

有趣的是,我在同樣的問題來了,我很驚訝人們upvoting對方的回答,因爲他清楚地詢問動態創建的組件,而不是下一個變量名已創建的組件這是可以獲得的,而不是匿名創建的對象。

答案很簡單。使用 getComponents()來遍歷添加到JPanel的組件數組。例如,使用instanceof查找要刪除的組件類型。在我的例子中,我刪除了添加到我的JPanel的所有JCheckBox。

Make sure to revalidate and repaint your panel, otherwise changes will not appear

組件是java.awt.Component.

//Get the components in the panel 
Component[] componentList = panelName.getComponents(); 

//Loop through the components 
for(Component c : componentList){ 

    //Find the components you want to remove 
    if(c instanceof JCheckBox){ 

     //Remove it 
     clientPanel.remove(c); 
    } 
} 

//IMPORTANT 
panelName.revalidate(); 
panelName.repaint();