Clearing JPanel
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 move开发者_Go百科s 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.
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.
}
}
I think this should work.
g.clearRect (0, 0, panel.getWidth(), panel.getHeight());
Also, you could keep the old location of the square and just clear that rather than clear the whole background.
精彩评论