使用Java中的键绑定和动作映射来获取按钮的快捷键 [英] using keybinding and Action Map in Java for shortcut keys for buttons

查看:113
本文介绍了使用Java中的键绑定和动作映射来获取按钮的快捷键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a program where I want to have shortcuts for all the buttons in my program. example ctrl+a executes button 1.

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

I also want these shortcuts to be user changeable

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

so this is the code i am using to add a key binding

   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来获取快捷方式

Now since i want these to be user changeable, i want to be able to use the "BUTTON ONE ID" on the third line to get its information. I want to be able to know what key i entered for it and whether or not you need to hold ctrl or alt for the shortcut

所以我希望以下代码

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执行此操作,或者是更好的方法。谢谢

How do I do this using the "BUTTON ONE ID" or is their a better way of doing this. Thanks

推荐答案

好的,这是一个快速示例,说明如何允许用户生成自己的击键。它基本上捕获 CTRL SHIFT ALT META 键的状态并记录最后一个无修饰符 按键。

Okay, this a quick example of how you might allow the user to generate their own key strokes. It basically captures the state of the CTRL, SHIFT, ALT and META keys and records the last none "modifier" key press.

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

It provides a simple getKeyStroke method to return the key stroked that would be generated by the configured states, in this example, you will find that it prints the KeyStroke when a key is "typed", which is done for debugging

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 可能是一个;)

Now, this is rough and ready. I had it print some interesting characters while I was testing so you might want to run through it and see which keys you might want to filter out (hint Caps Lock might be one ;))

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

Now, with this in hand, you just need to change the InputMap

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

它将自动更新绑定

这篇关于使用Java中的键绑定和动作映射来获取按钮的快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆