简体   繁体   English

如何将 arguments 传递给 KeyBinding 中的 AbstractAction?

[英]How do I pass an arguments to an AbstractAction in a KeyBinding?

I have the following keybindings:我有以下键绑定:

    InputMap iMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    ActionMap aMap = component.getActionMap();
    
    iMap.put(KeyStroke.getKeyStroke("shift LEFT"), "MOVE_LONG_LEFT");
    iMap.put(KeyStroke.getKeyStroke("LEFT"), "MOVE_LEFT");
    aMap.put("MOVE_LONG_LEFT", moveLeft);   // I WANT moveLeft TO RECEIVE 10 AS PARAMETER
    aMap.put("MOVE_LEFT", moveLeft);        // I WANT moveLeft TO RECEIVE 1 AS PARAMETER

I would want to add a parameter to moveLeft in the ActionMap, something like (pseudocode):我想在 ActionMap 中向 moveLeft 添加一个参数,例如(伪代码):

aMap.put("MOVE_LONG_LEFT", moveLeft, 10);
aMap.put("MOVE_LEFT", moveLeft, 1);

...

Action moveLeft = new AbstractAction(int steps) {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("moved Left " + steps + " steps");
    }
};

Is it possible to pass arguments in KeyBindings?是否可以在 KeyBindings 中通过 arguments ?

How do I pass an arguments to an AbstractAction如何将 arguments 传递给 AbstractAction

Create your Action as an inner class then you can save the parameter as in instance variable of your class:将您的Action创建为内部 class 然后您可以将参数保存为 class 的实例变量:

class MoveAction extends AbstractAction 
{
    private int steps;

    public MoveAction(int steps)
    {
        this.steps = steps;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("moved Left " + steps + " steps");
    }
};

Then you use the class like:然后你使用 class 像:

aMap.put("MOVE_LONG_LEFT", new MoveAction(10)); 
aMap.put("MOVE_LEFT", new MoveAction(1));  

See;看; Motion Using the Keyboard . 使用键盘的运动 The MotionWithKeyBindings example demonstrates this approach. MotionWithKeyBindings示例演示了这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM