user5554725
user5554725

Reputation:

JPanel drawString leaving strings

I have a JPanel here that I want to have keep track of a number of guesses that I am giving the player.

The guesses are displayed every time the paintcomponenent is called. This is the code:

@Override
public void paintComponent(Graphics g){
    if(stop) {
        g.drawString("YOU RAN OUT OF GUESSES. YOU LOSE!", getWidth() / 2 - 150, getHeight() / 2 - 5);
        return;
    }
    for(Block block : blocks){
        block.draw(g);
    }
    g.setColor(Color.LIGHT_GRAY);
    g.fillRect(650, 650, 100, 100);
    g.setColor(Color.BLACK);
    g.drawRect(650, 650, 100, 100);

    g.drawString("CHECK", 680, 705);
    g.drawString("Guesses Left: " + guesses, 100, 100);
}

What happens is the strings that are drawn from the previous calling of repaint() to cause this method to be called do not disappear.

This means that the number after "Guesses left: " gets to be unreadable after numbers start to pile on each other (starting from ten and going down once before the method is called).

I don't see a reason why this should be an issue. A similar issue I am having is that when the stop Boolean is true, it should be quitting the method and not draw the rest of the shapes. This is not the case though, all those shapes are still drawn.

Can someone help me figure out what I am doing wrong? Here is a screenshot of my two problems:

enter image description here

Also, through a bit of accidental testing, I found that if the window is resized, all the other shapes disappear and only the text is left.

Do I just have a misconception of how the repaint method works? My high school java teacher told me it essentially just recalls the paintComponent() method, but I wouldn't be surprised if that was incorrect.

Upvotes: 2

Views: 171

Answers (1)

camickr
camickr

Reputation: 324118

What happens is the strings that are drawn from the previous calling of repaint() ...

@Override
public void paintComponent(Graphics g)
{
    ...
}

You need to make sure the panels background is painted before you do your custom painting. The code should be:

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    ...
}

Upvotes: 4

Related Questions