Reputation: 435
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);
}
Upvotes: 2
Views: 5937
Reputation: 795
"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);
outside any if statements.
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
.
Upvotes: 0
Reputation: 13331
You should always call super.paintComponent(g);
(unless you really know what you are doing).
Put that call outside your if-statement. 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);
}
Upvotes: 5