Java Swing: Consumption of Key Events

I have a JFrame (containing various text fields and tables, etc.) and I want to install a hotkey function that is applied whenever the frame is open (a bit like a menu accelerator shortcut). It basically works, and my action gets called no matter which field or control has focus:

String MY_GLOBAL_ACTION_TRIGGER = "hotKey";
InputMap im = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
KeyStroke ks = KeyStroke.getKeyStroke('`');
im.put(ks, MY_GLOBAL_ACTION_TRIGGER);
ActionMap am = getRootPane().getActionMap();
am.put(MY_ACTION_TRIGGER, new AbstractAction() { public void actionPerformed() ... });

However, the keystroke is not consumed, and I still get the inverse quote inserted into the text box. How can I prevent a keystroke from spreading to text fields after invoking my action?

+4
source share
3 answers

Use KeyboardFocusManager and KeyEventDispatcher

private void myListener implements KeyEventDispatcher {
  public boolean dispatchKeyEvent (KeyEvent ke) {
    if (ke.getKeyChar() == '`') {
      MY_GLOBAL_ACTION.actionPerformed(null);
      return true;
    }
    return false;
  }
}
+2
source

, , ,

, / , ,

, textField, DocumentFilter

. DocumentFilter

+2

:

KeyStroke, char, -, . KeyStroke(KeyEvent key, int modifiers). , , , .

- :

public class KeyStrokeFrame extends JFrame {
    public static void main(String[] args) {
        new KeyStrokeFrame().setVisible(true);
    }

    public KeyStrokeFrame() {
        setSize(200, 200);
        JTextField jtf = new JTextField();
        getContentPane().add(jtf);
        String MY_GLOBAL_ACTION_TRIGGER = "hotKey";
        InputMap im = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_1, 0);
        ((AbstractDocument)jtf.getDocument()).setDocumentFilter(new DocumentFilter() {
            @Override
            public void insertString(FilterBypass fb, int offset,
                    String string, AttributeSet attr)
                    throws BadLocationException {
                if (string.equals("1")) return;
                super.insertString(fb, offset, string, attr);
            }

            @Override
            public void replace(FilterBypass fb, int offset, int length,
                    String text, AttributeSet attrs)
                    throws BadLocationException {
                if (text.equals("1")) return;
                super.replace(fb, offset, length, text, attrs);
            }
        });
        im.put(ks, MY_GLOBAL_ACTION_TRIGGER);
        ActionMap am = getRootPane().getActionMap();
        am.put(MY_GLOBAL_ACTION_TRIGGER, new AbstractAction() { 
            public void actionPerformed(ActionEvent e) {
                System.out.println("pressed");} 
            }); 
        }
}
+1

Source: https://habr.com/ru/post/1568807/


All Articles