Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing JPanel

Tags:

java

swing

I am making a program in which there is a square that changes its x and y positions when a key is pressed. The square moves but the the old square is still there. How do I remove/clear everything from a panel before I repaint it? Calling removeAll had no effect.

like image 491
Adrian D'Urso Avatar asked Jul 04 '26 08:07

Adrian D'Urso


1 Answers

Presumably your code includes custom paintComponent() logic. The key thing to observe is what does your panel look like when you do not override paintComponent()? An empty (or cleared) panel:

Thus the solution is to invoke the paintComponent() method of the parent type on the panel, before executing your custom paintComponent() logic:

public class CustomPanel extends JPanel {
  @Override
  public void paintComponent(Graphics g) {
    super.paintComponent(g); // first draw a clear/empty panel
    // then draw using your custom logic.
  }
}
like image 77
user268396 Avatar answered Jul 07 '26 14:07

user268396



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!