java 清除JPanel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7408034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Clearing JPanel
提问by Adrian D'Urso
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.
我正在制作一个程序,其中有一个正方形,当按下某个键时,它会改变其 x 和 y 位置。广场移动了,但旧广场还在。在重新粉刷面板之前,如何从面板上移除/清除所有内容?调用removeAll
没有效果。
采纳答案by user268396
Presumably your code includes custom paintComponent()
logic. The key thing to observe is what does your panel look like when you do notoverride paintComponent()
? An empty (or cleared) panel:
大概您的代码包含自定义paintComponent()
逻辑。要观察的关键是当您不覆盖时您的面板是什么样子的paintComponent()
?一个空的(或清除的)面板:
Thus the solution is to invoke the paintComponent()
method of the parent type on the panel, before executing your custom paintComponent()
logic:
因此,解决方案是paintComponent()
在执行自定义paintComponent()
逻辑之前调用面板上父类型的方法:
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.
}
}
回答by Mike K.
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.
此外,您可以保留广场的旧位置并清除它而不是清除整个背景。