Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I want the tank to move in the screen but it doesn't update at all. If I am going to draw a ball...an oval...it does move in the screen, but since I want a picture to do so, I used the image method, but why does it stay on the window and does not even move even with the key listener method? Here is what I did:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
 import javax.swing.ImageIcon;

import javax.swing.JPanel;
import javax.swing.JFrame;

public class Main extends JFrame{

Image tank;
 int x, y;
public class ActionListener extends KeyAdapter{


    public void keyPressed (KeyEvent e) {
        int key = e.getKeyCode();
            if (key == e.VK_LEFT) {
                x--;
            }
            if (key == e.VK_RIGHT) {
                x++;
            }
            if (key == e.VK_UP) {
                y--;
            }
            if (key == e.VK_DOWN) {
                y++;
            }
    }
    public void keyReleased (KeyEvent e) {

    }
}
public Main () {
    x = 300;
    y = 320;
    addKeyListener(new ActionListener());

    setSize(500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setVisible(true);

}

public void paint (Graphics g) {

    Graphics gr = (Graphics2D) g;
    gr.drawImage(tank,0,0, null);
    tank = new ImageIcon (this.getClass().getResource("tank.png")).getImage();

    repaint ();
}

public static void main (String args []) {

    new Main ();
}
}

how can i fix this so it updates and moves the picture as I wanted it to? I even plan on making separate pictures for each direction, but with this problem I can't move on. Thanks.

share|improve this question
    
Why do you first call drawImage, and then construct a new ImageIcon for the tank variable? That's weird –  Liosan Dec 24 '12 at 9:13

1 Answer 1

This is the error

public void paint (Graphics g) {
    Graphics gr = (Graphics2D) g;
    gr.drawImage(tank,0,0, null);
    tank = new ImageIcon (this.getClass().getResource("tank.png")).getImage();
    repaint ();
}

Change it to

public void paint (Graphics g) {
    Graphics gr = (Graphics2D) g;
    if (tank==null){
        tank = new ImageIcon (this.getClass().getResource("tank.png")).getImage();
    }
    gr.drawImage(tank,0,0, null);
    repaint ();
}

Though calling repaint from paint could blow out your program. See http://bit.ly/VjKahS

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.