Java键绑定

Java键绑定,第1张

Java键绑定

您要问的实际上是违反直觉的,并且违背了键绑定API的设计。

目的是为每个按键提供单个工作单元。在我看来,这建议您应为每个箭头键分别执行 *** 作

它使您更容易遵循逻辑,进行更改,根据需要规避 *** 作。

但是我是谁呢?

如果看不到它,一种简单的方法就是为每个动作分配一个“命令”,然后在

actionPerformed
触发该动作时可以进行询问。

public TestKeyBindings02() {    JPanel panel = new JPanel();    InputMap im = panel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);    ActionMap am = panel.getActionMap();    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "RightArrow");    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "LeftArrow");    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "UpArrow");    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "DownArrow");    am.put("RightArrow", new ArrowAction("RightArrow"));    am.put("LeftArrow", new ArrowAction("LeftArrow"));    am.put("UpArrow", new ArrowAction("UpArrow"));    am.put("DownArrow", new ArrowAction("DownArrow"));}public class ArrowAction extends AbstractAction {    private String cmd;    public ArrowAction(String cmd) {        this.cmd = cmd;    }    @Override    public void actionPerformed(ActionEvent e) {        if (cmd.equalsIgnoreCase("LeftArrow")) { System.out.println("The left arrow was pressed!");        } else if (cmd.equalsIgnoreCase("RightArrow")) { System.out.println("The right arrow was pressed!");        } else if (cmd.equalsIgnoreCase("UpArrow")) { System.out.println("The up arrow was pressed!");        } else if (cmd.equalsIgnoreCase("DownArrow")) { System.out.println("The down arrow was pressed!");        }    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5506090.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存