我只是用java进入用户输入。我最初从 KeyListener 开始,然后被告知使用 KeyBindings。当我按下右箭头键时,我似乎无法让动画测试移动。这是实现键绑定的正确方法,还是我需要在其中一种方法中添加一些东西?是否可以将所有输入方法(处理键绑定的方法)放入另一个可以访问的类中?我的主要问题是无法使用右箭头键移动动画测试。
public class EC{
Animation test = new Animation();
public static void main(String args[])
{
new EC();
}
public EC()
{
JFrame window=new JFrame("EC");
window.setPreferredSize(new Dimension(800,600));
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(test);
window.pack();
window.setVisible(true);
addBindings();
}
public void addBindings()
{
Action move = new Move(1,0);
Action stop = new Stop();
InputMap inputMap = test.getInputMap();
ActionMap actionMap = test.getActionMap();
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,Event.KEY_PRESS);
inputMap.put(key,"MOVERIGHT");
actionMap.put("MOVERIGHT",move);
key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,Event.KEY_RELEASE);
inputMap.put(key, "STOP");
actionMap.put("STOP", stop);
}
class Move extends AbstractAction
{
private static final long serialVersionUID = 1L;
int dx,dy;
public Move(int dx,int dy)
{
this.dx=dx;
this.dy=dy;
test.startAnimation();
test.update();
}
@Override
public void actionPerformed(ActionEvent e) {
test.x+=dx;
test.y+=dy;
test.repaint();
}
}
class Stop extends AbstractAction
{
int dx,dy;
private static final long serialVersionUID = 1L;
public Stop()
{
test.stopAnimation();
test.update();
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
dx=0;
dy=0;
test.repaint();
}
}
}