如何使用键事件调度程序进行键盘快捷键

时间:2017-05-18 13:44:34

标签: java swing

我想使用我的jframe或jdialog中的快捷键访问组件(EX:这里我使用Ctrl + N来访问jframe的NEW按钮),所以我能够使用键事件调度程序执行我的任务但是事情  当按下短按键时,相关的按键事件会递归地触发,我怎么能停止呢?我如何管理一次?这是我的代码。

public void FocuseComponent(JComponent component) {

    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {

            switch (e.getID()) {
                case KeyEvent.KEY_PRESSED:
                    if (e.getKeyCode() == e.VK_N) {
                        component.requestFocusInWindow();
                    }
                    break;

                case KeyEvent.KEY_RELEASED:

                    break;

                case KeyEvent.KEY_TYPED:
                    break;

            }

            return false;

        }

    });

}

}

1 个答案:

答案 0 :(得分:2)

以下是如何为窗口注册键绑定全局的示例:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class TestKeyHandling {

    private static final String CTRL_N_KEY = "nKey";
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                final JFrame frm = new JFrame("Test");
                Action act = new AbstractAction() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JOptionPane.showMessageDialog(frm, "Ctrl + N pressed!");
                    }
                };
                frm.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control N"), CTRL_N_KEY);
                frm.getRootPane().getActionMap().put(CTRL_N_KEY, act);
                frm.add(new JTextField(20), BorderLayout.NORTH);
                frm.add(new JTextField(20), BorderLayout.SOUTH);
                frm.pack();
                frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frm.setLocationRelativeTo(null);
                frm.setVisible(true);
            }
        });
    }
}