2

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):

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?

M.E.
  • 4,955
  • 4
  • 49
  • 128
  • _Is it possible to pass arguments in KeyBindings?_ No, it is not possible to pass arguments in [key bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) Maybe if you explained why you think you need to do that, someone may offer an alternative way to achieve the same result. – Abra Nov 28 '20 at 18:16
  • I have F1-F10 doing the same thing (i.e. calling the same function) but with a parameter changing from 1 to 10 depending on the function key pressed. If keybindings do not allow arguments I guess the only choice is to process the `ActionEvent e` where I understand there will be the key pressed. – M.E. Nov 28 '20 at 18:20

1 Answers1

3

How do I pass an arguments to an AbstractAction

Create your Action as an inner class then you can save the parameter as in instance variable of your 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:

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.

camickr
  • 321,443
  • 19
  • 166
  • 288