Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom keyboard shortcut in java

I am developing a java swing application. I want to add a keyboard shortcut say CTRL    + H. This should perform the same action performed by jButton1 when clicked.

This shortcut should behave in the same way even when jButton1 is not focused.

I tried with KeyEventDispatcher, but it doesn't seem to be working for me. Is there any other way?

like image 617
Gadoya Avatar asked Apr 12 '26 07:04

Gadoya


2 Answers

Ok - First I don't think there is a way to set application wide shortcuts in Java Swing(Refer this question). But for a component it is possible.

You have to use a create an Action for the KeyStroke. But for Windows I found this library very helpful.

    {
        KeyStroke cancelKeyStroke = KeyStroke
                .getKeyStroke((char) KeyEvent.VK_ESCAPE);
        Keymap map = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);
        map.addActionForKeyStroke(cancelKeyStroke, cancelKeyAction);
    }
    private static Action cancelKeyAction = new AbstractAction() {
        public void actionPerformed(ActionEvent ae) {
            Component comp = (Component) ae.getSource();
            Window window = SwingUtilities.windowForComponent(comp);
            if (window instanceof Dialog) {
                window.dispose();
            } else if (comp instanceof JTextComponent
                    && !(comp instanceof JFormattedTextField)) {
                JTextComponent tc = (JTextComponent) comp;
                int end = tc.getSelectionEnd();
                if (tc.getSelectionStart() != end) {
                    tc.setCaretPosition(end);
                }
            }
        }
    };
like image 121
Chan Avatar answered Apr 13 '26 19:04

Chan


I think the answer to your question can be found here http://docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#registerKeyboardAction%28java.awt.event.ActionListener,%20java.lang.String,%20javax.swing.KeyStroke,%20int%29

like image 25
Vinit Avatar answered Apr 13 '26 20:04

Vinit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!