0

Main class:

    public Main() {
    Frame f = new Frame();
    final Panel p = f.p;

    final Player player = new Player();

    Timer t = new Timer(UPDATE_PERIOD, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Graphics g = p.getGraphics();
            p.render(g);

            player.tick();
            player.render(g);

            g.dispose();
        }
    });
    t.start();
}

Player render method:

public void render(Graphics g) {
    g.drawImage(Images.get("player"), x, y, null);
}

The problem is, that all previous drawn images are still there. Example (when I change the drawn image's x or y): screenshot

Kritner
  • 13,557
  • 10
  • 46
  • 72
FLP
  • 2,050
  • 2
  • 14
  • 16
  • 1
    You need to clear the previous draw before drawing again: `g.clearRect(0, 0, getWidth(), getHeight());` – GiantTree May 13 '15 at 18:59
  • You will need to update the question with a more [complete example](http://stackoverflow.com/help/mcve) if you want answers which are not guessing. Right now we don't really understand what your code is doing. (What does `p.getGraphics()` do? What are you painting to?) – Radiodef May 13 '15 at 19:18
  • @Radiodef p is the class which extends JPanel. .getGraphics() is from the superclass. And it will be a small game I just begun and were trying around – FLP May 13 '15 at 19:23
  • Well then you have received answers. (Don't paint that way.) You should also look at my answer here: http://stackoverflow.com/a/30175751 which demonstrates a more proper way to do painting for a game and has links to other examples. – Radiodef May 13 '15 at 19:29

3 Answers3

2

Rather than doing custom rendering your your timer, you should really be doing all your painting in your paintComponent method. Something like:

   public void actionPerformed(ActionEvent e) {            
        player.tick();
        p.repaint();
    }

And then re-render the player and the background in paintComponent()

Painting like you currently are runs into issues when you resize the panel, etc

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
2

To draw in Swing, you should not be getting the Graphics object directly from the JPanel. Instead, override the paintComponent method and use the parameter Graphics object to perform your custom drawing, with a call to the parent method to erase previous painting

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    //custom painting goes here
}

If you wish to trigger a repaint, use the method by that name on the JPanel:

p.repaint();
copeg
  • 8,290
  • 19
  • 28
0

Try calling 'p.repaint()' in your ActionListener once you have changed the position of the Graphic.

Jesse D.
  • 11
  • 6