0

我只是用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();
        }

    }




}
4

1 回答 1

1

很难确定,但你可能想尝试类似的东西test.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)

KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,Event.KEY_PRESS);也不对。第二个参数是修饰符属性,用于ctrl,altshift

在你的情况下KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);会更正确

如果您对按下键时开始调用的操作感兴趣,请使用类似...

KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false);

或者,如果您只想知道它何时发布,请使用类似

KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true);
于 2013-07-26T05:56:23.353 回答