1

I'm trying to make a 2D game, but I can't figure out why my graphics from precedent frames are still there. The effect is when moving a rectangle on x with 1 pixel / frame, I get a long bar drawn on my screen.

In the class body I declared the objects beneath like that:

private int x, y;
private BufferedImage image;
private Graphics2D g;

This is how I'm initializing:

x = 10, y = 25;
image = new BufferedImage(300, 300, BufferedImage.TYPE_INT_BGR);
g = (Graphics2D) image.getGraphics();
r = new Rectangle(x, y, 10, 10);

I have method where I draw graphics:

Graphics g2 = this.getGraphics();
g2.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.draw(r);
g2.dispose();

I also have a tick method where I move the rectangle:

x++;

The class extends Canvas and implements Runnable for the game loop and I use a JFrame object .

This is the result of 10x10 rectangle movement: capture

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Xander
  • 11
  • 1
  • 1
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). 3) Note that a buffered image will store all previous drawings. To negate that, fill it with a BG color (or clear it) before drawing the latest part of the game. – Andrew Thompson Apr 01 '16 at 12:05
  • 2
    `Graphics g2 = this.getGraphics();` If 'this' is a component, that is doing it wrong. But I won't speculate further (because I detest guessing). Post an MCVE. – Andrew Thompson Apr 01 '16 at 12:07
  • 1
    For [example](http://stackoverflow.com/a/3256941/230513). – trashgod Apr 01 '16 at 15:01

0 Answers0