How To Capture Key Events With JFrame or Window

4 years ago by in AWT, How To, Swing Tagged: , , , , , ,

We can capture all keys typed while the JFrame or Windows is active using the following example.

KeyEventDispatcher keyEventDispatcher = new KeyEventDispatcher() {
  @Override
  public boolean dispatchKeyEvent(final KeyEvent e) {
    if (e.getID() == KeyEvent.KEY_TYPED) {
      System.out.println(e);
    }
    // Pass the KeyEvent to the next KeyEventDispatcher in the chain
    return false;
  }
};
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyEventDispatcher);

In the above example the dispatchKeyEvent() method returns false, which means that the KeyboardFocusManager will pass this KeyEvent to the next KeyEventDispatcher in the chain. If we want to stop the KeyEvent from being passed over, then we simply return true.

Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 SearchSecurity.co.UK award (Website).

Leave a Comment