18

I am adding and deleting components dynamically in a JPanel. Adding and deleting functionality works fine but when I delete the component it deletes the last component rather than the component to be deleted.

How can I solve this issue?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ManthanB
  • 404
  • 2
  • 5
  • 21
  • 4
    Please post your code so we can help. – Nate W. Aug 19 '11 at 05:34
  • 7
    For better help sooner, include an [SSCCE](http://www.sscce.org) – mre Aug 19 '11 at 13:32
  • 3
    Are you using the method "public void remove(int index)" instead of "public void remove(Component comp)"? Post an SSCCE if you want a better answer. – Santosh Tiwari Aug 23 '11 at 20:18
  • +1 for `CardLayout` - makes life much easier if you have a pool of components to show at different times. Thanks for reminding me of it, @Andrew. – Paul Dec 02 '11 at 00:01

2 Answers2

24

Interestingly enough I am coming across the same issue and I am surprised people are upvoting the other answer, as he is clearly asking about dynamically created Components, not components already created under a variable name which is obtainable, instead of anonymously created objects.

The answer is pretty simple. Use getComponents() to iterate through an array of components added to the JPanel. Find the kind of component you want to remove, using instanceof for example. In my example, I remove any JCheckBoxes added to my JPanel.

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

Component is from 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();
Community
  • 1
  • 1
Billy Bob
  • 344
  • 2
  • 10
  • 2
    The revalidate bit is what worked for me. What was interesting to me was, after initializing the panel with a particular component, I didn't need repaint() on the first revalidate(). On subsequent revalidations, I needed to repaint() as well. – Akshay Gaur Mar 30 '18 at 06:03
11

Using the method Container.remove(Component), you can remove any component from the container. For example:

JPanel j = new JPanel();

JButton btn1 = new JButton();

JButton btn2 = new JButton();

j.add(btn1);

j.add(btn2);

j.remove(btn1);
fireshadow52
  • 6,298
  • 2
  • 30
  • 46
Noah Singer
  • 526
  • 2
  • 6
  • 17