如何将参数传递给 KeyBinding 中的 AbstractAction?
How do I pass an arguments to an AbstractAction in a KeyBinding?
我有以下键绑定:
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
我想在 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");
}
};
是否可以在 KeyBindings 中传递参数?
How do I pass an arguments to an AbstractAction
将您的 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");
}
};
然后你使用 class 比如:
aMap.put("MOVE_LONG_LEFT", new MoveAction(10));
aMap.put("MOVE_LEFT", new MoveAction(1));
见; Motion Using the Keyboard。 MotionWithKeyBindings
示例演示了这种方法。
我有以下键绑定:
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
我想在 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");
}
};
是否可以在 KeyBindings 中传递参数?
How do I pass an arguments to an AbstractAction
将您的 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");
}
};
然后你使用 class 比如:
aMap.put("MOVE_LONG_LEFT", new MoveAction(10));
aMap.put("MOVE_LEFT", new MoveAction(1));
见; Motion Using the Keyboard。 MotionWithKeyBindings
示例演示了这种方法。