Control Image with Arrow Keys

2019-09-02 18:48发布

问题:

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);
    }


}

回答1:

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



回答2:

@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
          }
       }
   });

}