0

I want to move a image across the screen by 16 to the right when the arrow key is pressed. I want to move it with a speed(1px/10ms) until reaches the point. The image is created inside a class that is child of JPanel. I wrote the next code but the image changes the position instatly instead making a movement:

public class Test extends JFrame implements KeyListener {
    private int x=0;
    private int y=0;
    BufferedImage img;
    ...
    ...
    public void paint(Graphics g){
        g.drawImage(img,x,y,null);
    }
    // Move to a point 16 pixels to right
    public void moveRight(){
        for(int i=0;i<16;i++){
            x++;
            repaint();
            try {
                Thread.sleep(10); // Sleep 10 milliseconds until next position change
            }catch (InterruptedException e) {}
        }
    }

    public void keyPressed(KeyEvent e) {
         if(e.getKeyCode()==KeyEvent.VK_RIGHT){
             moveRight();
         }
    }
}
Alejandro Garcia
  • 1,171
  • 1
  • 11
  • 22

2 Answers2

4

The problem is your sleep inside the EDT (Event-Dispatching-Thread). repaint() triggers an event that will be dispatched by the EDT and will in turn perform the actual repainting of your component. Since you are blocking the EDT, the repaint does not perform directly (but after the end of all your code then a single repaint event occurs (because repaint events are grouped whenever possible). You will probably need to use SwingWorker to fix this issue.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • 4
    +1 A `javax.swing.Timer`, shown [here](http://stackoverflow.com/q/9849950/230513), is an alternative to `SwingWorker` in this context. – trashgod Apr 20 '12 at 23:44
2

What if you call moveRight() in another thread?

try this:

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode()==KeyEvent.VK_RIGHT){
        new Thread(new Runnable(){
            public void run(){
                moveRight();
            }
        }).start();
    }
}

I've not tested and I even don't know if this is a good aproach

DaniGio
  • 31
  • 3