使用Java中的键绑定和Action Map获取按钮

时间:2017-10-28 03:24:35

标签: java swing key-bindings

我正在创建一个程序,我想在程序中为所有按钮提供快捷方式。例子ctrl + a执行按钮1.

我还希望这些快捷方式可由用户更改

所以这是我用来添加密钥绑定的代码

   InputMap IM = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

   IM.put(KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_DOWN_MASK | 
          InputEvent.ALT_DOWN_MASK), "BUTTON ONE ID");

  ActionMap actionMap = component.getActionMap();
    actionMap.put("BUTTON ONE ID", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            actionListener.actionPerformed(e);
        }
    });

现在,因为我希望这些用户可以更改,我希望能够使用" BUTTON ONE ID"在第三行获取其信息。我希望能够知道我为它输入了什么键,以及是否需要按住ctrl或alt来显示快捷方式

所以我想要以下代码

if("BUTTON ONE ID"){
  //print KeyEvent/keyCode info and if we need to hold ctrl, alt or shift?
  //and then i want to be able to change the key bindings 

}

如何使用" BUTTON ONE ID"或者是他们这样做的更好方法。谢谢

1 个答案:

答案 0 :(得分:2)

好的,这是一个快速示例,说明如何允许用户生成自己的击键。它基本上捕获 CTRL SHIFT ALT META 键的状态并记录最后一个&# 34;改性剂"按键。

它提供了一个简单的getKeyStroke方法来返回由配置状态生成的描边键,在这个例子中,当一个键是&#34时,你会发现它打印KeyStroke ;键入",用于调试

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class ExampleLKeyConfig {

    public static void main(String[] args) {
        new ExampleLKeyConfig();
    }

    public ExampleLKeyConfig() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new KeyCapturePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class KeyCapturePane extends JPanel {

        private JToggleButton ctrlKey;
        private JToggleButton altKey;
        private JToggleButton shiftKey;
        private JToggleButton metaKey;
        private JButton strokeKey;

        private int keyCode;

        public KeyCapturePane() {
            setBorder(new EmptyBorder(10, 10, 10, 10));
            setLayout(new GridBagLayout());

            ctrlKey = new JToggleButton(KeyEvent.getModifiersExText(KeyEvent.CTRL_DOWN_MASK));
            altKey = new JToggleButton(KeyEvent.getModifiersExText(KeyEvent.ALT_DOWN_MASK));
            shiftKey = new JToggleButton(KeyEvent.getModifiersExText(KeyEvent.SHIFT_DOWN_MASK));
            metaKey = new JToggleButton(KeyEvent.getModifiersExText(KeyEvent.META_DOWN_MASK));
            strokeKey = new JButton("-");

            updateMetaState(new KeyEvent(this, 0, 0, 0, 0, ' '));

            add(ctrlKey);
            add(altKey);
            add(shiftKey);
            add(metaKey);
            add(strokeKey);

            setFocusable(true);
            addKeyListener(new KeyAdapter() {

                @Override
                public void keyPressed(KeyEvent e) {
                    updateMetaState(e);
                    int code = e.getKeyCode();
                    if (code != KeyEvent.VK_CONTROL && code != KeyEvent.VK_ALT && code != KeyEvent.VK_SHIFT && code != KeyEvent.VK_META) {
                        strokeKey.setText(KeyEvent.getKeyText(code));
                        keyCode = code;
                    }
                }

                @Override
                public void keyReleased(KeyEvent e) {
                }

                @Override
                public void keyTyped(KeyEvent e) {
                    System.out.println(getKeyStroke());
                }

            });

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    requestFocusInWindow();
                }
            });
        }

        protected int getModifiers() {
            return (ctrlKey.isSelected() ? KeyEvent.CTRL_DOWN_MASK : 0)
                            | (altKey.isSelected() ? KeyEvent.ALT_DOWN_MASK : 0)
                            | (shiftKey.isSelected() ? KeyEvent.SHIFT_DOWN_MASK : 0)
                            | (metaKey.isSelected() ? KeyEvent.META_DOWN_MASK : 0);
        }

        public KeyStroke getKeyStroke() {
            return KeyStroke.getKeyStroke(keyCode, getModifiers());
        }

        protected void updateMetaState(KeyEvent evt) {
            updateMetaState(ctrlKey, evt.isControlDown());
            updateMetaState(altKey, evt.isAltDown());
            updateMetaState(shiftKey, evt.isShiftDown());
            updateMetaState(metaKey, evt.isMetaDown());
        }

        protected void updateMetaState(JToggleButton btn, boolean isPressed) {
            if (isPressed) {
                btn.setSelected(!btn.isSelected());
            }
        }

    }

}

现在,这已经很准备了。我在测试时打印了一些有趣的字符,所以你可能想要浏览它并看看你想要过滤掉哪些键(提示 Caps Lock 可能是一个;)

现在,有了这个,您只需要更改InputMap

KeyStroke ks = ...;
IM.put(ks, "BUTTON ONE ID");

它将自动更新绑定