Control Image with Arrow Keys

2019-09-02 19:00发布

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


}

2条回答
对你真心纯属浪费
2楼-- · 2019-09-02 19:08

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

查看更多
一夜七次
3楼-- · 2019-09-02 19:16
@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
          }
       }
   });

}
查看更多
登录 后发表回答