[英]Clear all graphics from screen Java
I'm working on a small game and I want to set the condition for defeat. 我正在做一个小型游戏,我想设定失败的条件。 If defeat is true, I want all the graphics on the screen to be cleared so I can make way for some output text on the screen.
如果失败是真的,我希望清除屏幕上的所有图形,以便为屏幕上的某些输出文本让路。
I would assume there is a conventional way to do this (which I would rather know than having to put in unnecessary code). 我认为有一种常规方法可以做到这一点(我宁愿知道这种方法,而不必输入不必要的代码)。 Thanks in advance!
提前致谢!
Here is my code so far: 到目前为止,这是我的代码:
public void paintComponent(Graphics g){
if (!defeat){
super.paintComponent(g);
square.display(g);
wall.display(g);
for (Circle circle: circleArray){
circle.display(g);
}
}else if(defeat){
g.drawString("You have been defeated", 300, 300);
}
You should always call super.paintComponent(g);
您应该始终调用
super.paintComponent(g);
(unless you really know what you are doing). (除非您真的知道自己在做什么)。
Put that call outside your if-statement. 将该呼叫放在您的if语句之外。 That call is what "clears the screen".
该呼叫就是“清除屏幕”。 Like this:
像这样:
public void paintComponent(Graphics g){
super.paintComponent(g);
if (!defeat){
square.display(g);
wall.display(g);
for (Circle circle: circleArray){
circle.display(g);
}
}else if(defeat){
g.drawString("You have been defeated", 300, 300);
}
"I want all the graphics on the screen to be cleared so I can make way for some output text on the screen"
, but you also want the screen to be cleared every frame, so you basically need to always clear it, meaning you should put super.paintComponent(g);
"I want all the graphics on the screen to be cleared so I can make way for some output text on the screen"
,但是您还希望每帧都清除屏幕,因此您基本上需要始终对其进行清除,这意味着您应该把super.paintComponent(g);
outside any if statements. 在任何if语句之外。
I'd recommend this code: (I've cleaned it up and moved the frame clear) 我建议使用以下代码:(我将其清理干净并移开了框架)
public void paintComponent(Graphics g){
super.paintComponent(g);
if (defeat){
g.drawString("You have been defeated", 300, 300);
} else {
square.display(g);
wall.display(g);
for (Circle circle: circleArray)
circle.display(g);
}
}
I'd also recommend changing the variable defeat
to defeated
and giving the Graphics object a better name, like I use canvas
. 我还建议将变量
defeat
改为defeated
并给Graphics对象起一个更好的名字,就像我使用canvas
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.