Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

How can I listen for key presses (within Java Swing) across all components?

I would like to listen for key combinations such as Control+S without adding key listeners to each component in my Swing application. How can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is possible.

KeyboardFocusManager.getCurrentKeyboardFocusManager()
  .addKeyEventDispatcher(new KeyEventDispatcher() {
      @Override
      public boolean dispatchKeyEvent(KeyEvent e) {
        System.out.println("Got key event!");
        return false;
      }
});

That will grab all key events. Returning false allows the keyboard focus manager to resume normal key event dispatching to the various components.

If you want to catch key combos, you can keep a set of "pressed keys." Whenever a key is pressed, add it to the set and check what keys are already in the set. When a key is released, remove it from the set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...