0

我试图让我的图像根据我使用的箭头键在屏幕上移动。现在它不响应我按下的任何键。出于测试目的,我只尝试使用 RIGHT 箭头键。按下键时如何让图像响应?这是我到目前为止所拥有的:

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


}
4

2 回答 2

2

有关使用KeyListener 的问题以及使用 Key Bindings 的更好解决方案,请参阅Motion Using the Keyboard 。

于 2013-07-25T19:51:05.750 回答
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
          }
       }
   });

}
于 2013-07-25T17:23:21.370 回答