【问题标题】:Use KeyBindings使用键绑定
【发布时间】:2013-07-26 05:43:41
【问题描述】:

我刚刚使用 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();
        }

    }




}

【问题讨论】:

标签: java swing input action key-bindings


【解决方案1】:

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

另外KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,Event.KEY_PRESS); 也不正确。第二个参数是修饰符属性,用于 ctrlaltshift 等。

在你的情况下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);

【讨论】:

    猜你喜欢
    • 2018-10-14
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    相关资源
    最近更新 更多