我正在使用此代码来检测用户何时按下程序中的箭头键。我需要将按下的箭头键发送到一个方法,该方法将处理它并执行它需要做的事情。它的工作正常,但问题是我的代码是愚蠢的长和重复的,我确信这是一种缩短它的方法。我可以传递整数0-3而不是字符串,如果它使这更容易。这是我现在的代码:
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right");
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "up");
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "down");
getRootPane().getActionMap().put("left", new AbstractAction(){
public void actionPerformed(ActionEvent e)
{
close("left");
}
});
getRootPane().getActionMap().put("right", new AbstractAction(){
public void actionPerformed(ActionEvent e)
{
close("right");
}
});
getRootPane().getActionMap().put("up", new AbstractAction(){
public void actionPerformed(ActionEvent e)
{
close("up");
}
});
getRootPane().getActionMap().put("down", new AbstractAction(){
public void actionPerformed(ActionEvent e)
{
close("down");
}
});
答案 0 :(得分:1)
将常用功能抽象为方法:
private void mapKey(String keyStroke, final String command) {
Action action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
close(command);
}
};
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke(keyStroke), action);
getRootPane().getActionMap()
.put(action, action);
}
然后你可以这样做:
mapKey("LEFT", "left");
mapKey("RIGHT", "right");
mapKey("UP", "up");
mapKey("DOWN", "down");
答案 1 :(得分:0)
创建一个扩展AbstractAction的内部类,可以获取字符串参数
类似这样的事情
private class CloseAction extends AbstractAction {
private final String action;
public CloseAction(String anAction) {
action = anAction;
}
public void actionPerformed(ActionEvent e) {
close(action);
}
}
然后:
getRootPane().getActionMap().put("up", new CloseAction("up"));