0

Hey guys I have a little issue here. I have a panel where I am drawing a string. This is a game so I keep redrawing the score in order to update it. However when I draw it again it is drawn on top of the previous score so it looked all garbled up. Any ideas how to fix this?

comp2d.drawString(GetScore(Score),ScoreX,ScoreY);

user69514
  • 26,935
  • 59
  • 154
  • 188
  • 2
    Sounds like your panel's background isn't being cleared during the redraw process. If you can provide some more details (code) on how you're repainting it will help to work out what the problem is. – Ash Apr 12 '10 at 01:55

3 Answers3

5

You need to redraw the background, before you paint the string. If this is an ordinary panel, you can redraw the background by a call to super.paintComponent(g) in your own paintComponent; however, since this is a game, I am going to guess that you have some other background you need to draw. Also, I would suggest that you use a JLabel, in lieu of using thedrawString command, if possible.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
  • 2
    +1, I don't know why people keep trying to do custom painting like drawing strings and images on a panel when you can just use a JLabel. Use a proper layout manager and you don't have to worry about all these little painting details. – camickr Apr 12 '10 at 02:14
  • yeah I tried a JLabel, but for some reason when I add it everything else disappears – user69514 Apr 12 '10 at 04:33
1

You can try to use repaint() after comp2d.drawString().

zs2020
  • 53,766
  • 29
  • 154
  • 219
  • This solved my problem. Sometimes my new string would draw on top of my old one, but it doesn't after dropping repaint() after drawString(). – traderjosh Mar 13 '18 at 02:34
0

when you call this comand: comp2d.drawString(GetScore(Score),ScoreX,ScoreY);

You should call this : comp2d.dispose()

because all operations with comp2d will be applied after .dispose()

Dmitry
  • 87
  • 1
  • 2
  • **From review queue**: May I request you to please add some more context around your answer. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. – RBT May 13 '17 at 09:36