Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a shortcut for special keys in Java Swing, e.g. german umlaut key Ä?

How do I define a keyboard shortcut for top level special keys like german umlaut key Ä? I found a way to map unicode letters that are used for default american layout keys, see here. But the key event for the german umlaut key Ä is:

java.awt.event.KeyEvent[KEY_PRESSED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='ä',keyLocation=KEY_LOCATION_STANDARD,rawCode=222,primaryLevelUnicode=228,scancode=40] on frame0 

The idea is to register a keyboard action:

import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;


public class KeyStrokeForGermanUmlaut {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.setPreferredSize(new Dimension(600, 400));
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JPanel panel = new JPanel();
                final JLabel label = new JLabel("Text shall change with shortcut");
                panel.add(label);
                panel.registerKeyboardAction(new AbstractAction() {
                    @Override
                    public void actionPerformed(ActionEvent event) {
                        label.setText("It is working!!!");
                    }
                }, KeyStroke.getKeyStroke("control typed Ä"), JComponent.WHEN_IN_FOCUSED_WINDOW);

                frame.getContentPane().add(panel);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
like image 579
jan Avatar asked Apr 03 '14 09:04

jan


People also ask

How do I create a shortcut key in Java?

A JButon can generate an ActionListener interface when the button is pressed or clicked, it can also generate the MouseListener and KeyListener interfaces. We can also set the short cut keys for a JButton using the setMnemonic() method.

What are the 3 common shortcut keys?

Ctrl + C -- Copy selected text. Ctrl + X -- Cut selected text. Ctrl + N -- Open new/blank document.

Which shortcut key is A?

For example, the keyboard shortcut to select all text is Ctrl + A . To use this shortcut, press and hold down Ctrl , then press A , then let go of both keys.


2 Answers

  • you can to conjuring with JLabel, nothing happends for KeyEvents

  • should be start point with moving the focus to JFrames ContentPane (can be used as JPanel, but has BorderLayout in compare with plain JPanel - FlowLayout)

-

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class KeyStrokeForGermanUmlaut {

    private JFrame frame = new JFrame();
    private JLabel label = new JLabel("Text shall change with shortcut");

    public KeyStrokeForGermanUmlaut() {
        frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK), "CTRL + A");
        frame.getRootPane().getActionMap().put("CTRL + A", updateCol());
        frame.setPreferredSize(new Dimension(600, 100));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(label);
        frame.pack();
        frame.setLocation(150, 150);
        frame.setVisible(true);
    }

    private Action updateCol() {
        return new AbstractAction("Hello World") {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setText(label.getText() + " presses");
            }
        };
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new KeyStrokeForGermanUmlaut();
            }
        });
    }
}

.

.


EDIT see description in API getKeyStroke/ v.s. getKeyStrokeForEvent

then result is could be (little bit lost when and how to use modifiers SHIFT with uppercase form (ä and ú) for those two chars, maybe someone will help us with those pieces of KeyEvents)

enter image description here

from

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class KeyStrokeForGermanUmlaut {

    private JFrame frame = new JFrame();
    private JLabel label = new JLabel("Text shall change with shortcut");

    public KeyStrokeForGermanUmlaut() {
        frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke("typed ä"), "typed ä");
        frame.getRootPane().getActionMap().put("typed ä", updateCol());
        frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke("typed ú"), "typed ú");
        frame.getRootPane().getActionMap().put("typed ú", updateCol1());
        frame.setPreferredSize(new Dimension(600, 100));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(label);
        frame.pack();
        frame.setLocation(150, 150);
        frame.setVisible(true);
    }

    private Action updateCol() {
        return new AbstractAction("Hello World") {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setText(label.getText() + " presses - ä");
            }
        };
    }

    private Action updateCol1() {
        return new AbstractAction("Hello World") {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setText(label.getText() + " presses - ú");
            }
        };
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new KeyStrokeForGermanUmlaut();
            }
        });
    }
}
like image 81
mKorbel Avatar answered Sep 28 '22 16:09

mKorbel


I am afraid there is something fishy in the handling of modifiers for CTRL. That is: when inspecting the received key modifier=InputEvent.CTRL_MASK, extended modifier=InputEvent.CTRL_DOWN_MASK. And the API's javadoc is a bit suspicious.

Apart from that, Ä is not a special case, when "control" is left out.

To make it work, I had to add a dirty hack: register a key listener, that calls the action itself. I must be overseeing something.

For the rest I used an InputMap/ActionMap as intended. The input map does not seem to work, but to my understanding it does not work if added to a JTextField, or in the other answer (for Ä). The following works - in a horrible way.

final JLabel label = new JLabel("Text shall change with shortcut");
final KeyStroke key = KeyStroke.getKeyStroke((Character)'k',
        InputEvent.CTRL_DOWN_MASK, false);
final Object actionKey = "auml";
final Action action = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent event) {
        System.out.println("aha");
        label.setText("It is working!!!");
    }
};
label.addKeyListener(new KeyAdapter() {

    @Override
    public void keyPressed(java.awt.event.KeyEvent e) {
        if (e.isControlDown() && e.getKeyChar() == 'ä') {
            System.out.println("Ctrl-ä");
            label.getActionMap().get(actionKey).actionPerformed(null);
            // return;
        }
        super.keyPressed(e);
    }
});
label.getInputMap().put(key, actionKey);
label.getActionMap().put(actionKey, action);
like image 43
Joop Eggen Avatar answered Sep 28 '22 18:09

Joop Eggen