有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java按钮键盘快捷键

我有两个JButton,我希望在JFrame有焦点时允许键盘箭头键使用它们

有人能给我指出正确的方向吗


共 (3) 个答案

  1. # 1 楼答案

    要截取键(不必担心特定组件是否处于焦点),应该使用InputMap。请仔细阅读,例如:

    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html

    然后求WHEN_IN_FOCUSED_WINDOW常数

    除非所讨论的按钮仅调用单个方法,否则“按钮所做的一切”的最佳方法是:

    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            ((AbstractButton) c).doClick();
        }
    });
    
  2. # 2 楼答案

    当你说你想让他们使用“箭头键”时,我想你的意思是你想转移注意力。如果是这种情况,请阅读Swing教程中关于How to Use the Focus Subsystem的部分。它给出了一个如何使用Enter键进行此操作的示例

  3. # 3 楼答案

    从Swing的Action演示中修改

    按钮的初始化:

    // Sets the mnemonic to down, with no hint display
    JButton down = new JButton(new DownAction("Down", null, "This is the down button", new Integer(KeyEvent.VK_DOWN));
    

    行动:

    class DownAction extends AbstractAction {
        public DownAction(String text, ImageIcon icon,
                      String desc, Integer mnemonic) {
            super(text, icon);
            putValue(SHORT_DESCRIPTION, desc);
            putValue(MNEMONIC_KEY, mnemonic);
        }
        public void actionPerformed(ActionEvent e) {
            displayResult("Action for first button/menu item", e);
        }
    }