简体   繁体   中英

How to Use Key event dispatcher for keyboard shortcuts

I want to access component using shortcut keys in my jframe or jdialog(EX: Here i am using Ctrl+N to access NEW Button of the jframe),so I was able to do my task using key event dispatcher but t the thing is when press short key, relevant key event fire recursively how can i stop that? How can i manage that for a once? here is my code.

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;

        }

    });

}

}

Here is an example how to register a key binding global for a window:

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);
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM