javaswingjlayeredpane

JLayeredPane remove(int) method throws no such child


I am Creating JLayeredPane (mainFrame) and add stuff to it like this:

JPanel textP= new Scribe(text); //this returns panel with xome text
textP.setVisible(true);
mainFrame.add(shakespeare, new Integer(6));/*This is important!!!*/
mainFrame.repaint();
mainFrame.validate();

Later I am trying to remove it like this

mainFrame.remove(6);

and it throws No such child: 6. Other elements drawing images work fine:

JPanel imageP = new ImagePanel(image);
imageP.setVisible(true);
mainFrame.add(imageP, new Integer(5));
mainFrame.repaint();
mainFrame.validate();
//after a while
mainFrame.remove(5);

These panels are placed and removed from the pane with different order and timings defined by user input.


Solution

  • remove(int) removes the n'th component from the container, it doesn't relate to the layer the component was added to

    The best thing is to try a remove the component by its reference, as it's not always possible to know that anything was added/inserted before your component since you added it