0

I am trying to get my image to move across the screen based on what arrow keys I use. Right now it does not respond to any key I press. For testing purposes I have only tried implementing the use of the RIGHT arrow key. How would I get the image to respond when the key is pressed? This is what I have so far:

import java.applet.Applet; 
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;


public class EC extends Applet{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    int x=50;
    int y=50;
    int dx,dy;
    public void keyPressed(KeyEvent e)
    {
        int keyCode = e.getKeyCode();
        if(keyCode==KeyEvent.VK_RIGHT)
        {
            dx=1;
            x+=dx;
        }
    }
    public void keyReleased(KeyEvent e)
    {
        int keyCode = e.getKeyCode();
        if(keyCode==KeyEvent.VK_RIGHT)
        {
            dx=0;
        }
    }
    public void paint(Graphics g)
    {
        g.drawImage(IllustrationManager.player[0][0],x,y,null);
    }


}
user1058860
  • 513
  • 2
  • 9
  • 21
  • 1
    Use [*Key Bindings*](http://download.oracle.com/javase/tutorial/uiswing/misc/keybinding.html), for [example](http://stackoverflow.com/a/5797965/230513). – trashgod Jul 25 '13 at 17:41

2 Answers2

2

See Motion Using the Keyboard for the problems with using a KeyListener and a better solution which uses Key Bindings.

camickr
  • 321,443
  • 19
  • 166
  • 288
0
@Override
public void init(){
   addKeyListener(new KeyAdapter(){
       public void keyPressed(KeyEvent e)
       {
          int keyCode = e.getKeyCode();
          if(keyCode==KeyEvent.VK_RIGHT)
          {
              dx=1;
              x+=dx;
              this.repaint(); // forgot this initially
          }
       }
   });

}
bluedevil2k
  • 9,366
  • 8
  • 43
  • 57