Search code examples
javaswingjpaneljbuttonremovechild

Java - Removing the panel where the button is located


Is it possible that when i click the button that is located in a certain panel, that panel will be removed?

like

public void actionPerformed(ActionEvent e) {
    if(e.getSource()==removebutton)
        System.out.println("ok");
    removebutton.getRootPane().remove(cartpanel);

}

i'M Trying to make a shopping cart wherein when the customer view the cart, he will see the items located in a panel that have a remove button. Then when he clicks that button, the panel will be removed.

my code above is not doing the expected output, but is there any method that should be used with that?

panel http://dl.dropbox.com/u/62021435/Untitled.png


Solution

  • You can use Component#getParent to get a reference to the parent container. You would then need to get the Container's parent and remove the button's container from it...

    Container myParent = removebutton.getParent();
    Container parent = myParent.getParent();
    parent.remove(myParent);