2

How can I detect the Windows key modifier for KeyEvent? I have add the code:

textField.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        if ((e.getKeyCode() & KeyEvent.VK_ESCAPE) == KeyEvent.VK_ESCAPE) {
            textField.setText("");
        }
    }
});

But the problem is, when I use the Windows zoom and try to exit from it using Win + Escape, if focus is in TextField, its content clears. I've tried filter by e.getModifiersEx(), but it returns 0. The only way I've found is to detect whether Windows pressed or not, is to create boolean field and change it's value when Windows pressed/released.

So, is there any way to get the Windows key pressure state from KeyEvent for ESCAPE released event?

SeniorJD
  • 6,946
  • 4
  • 36
  • 53
  • This post may help: http://stackoverflow.com/questions/7851505/how-can-a-keylistener-detect-key-combinations-e-g-alt-1-1. – longhua Nov 19 '14 at 09:50
  • Yes, I know about `KeyStrokes`, but is there any way to do that by `KeyListener` only? – SeniorJD Nov 19 '14 at 09:55
  • It might be difficult. From the tutorial (https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html), it will send several events when a key combination is pressed. Have you ever tried `KeyEvent.getModifiers`? – longhua Nov 19 '14 at 09:58
  • of course, i've tried both `getModifiers` and `getMofidiersEx()` – SeniorJD Nov 19 '14 at 10:06

1 Answers1

0

The way I used for myself:

AbstractAction escapeAction = AbstractAction() {
    public void actionPerfomed(ActionEvent e) {
        setText("");
    }
}

textField.addCaretListener(new CaretListener() {
    @Override
    public void caretUpdate(CaretEvent e) {
        if (textField.getText() == null || textField.getText().isEmpty()) {
            textField.getActionMap().remove("escape");
            textField.getInputMap().remove(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));
        } else {
            textField.getActionMap().put("escape", escapeAction);
            textField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), escapeAction);
        }
    }
});
SeniorJD
  • 6,946
  • 4
  • 36
  • 53