How To Capture Key Events With JFrame or Window

5 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() {
  public boolean dispatchKeyEvent(final KeyEvent e) {
    if (e.getID() == KeyEvent.KEY_TYPED) {
    // Pass the KeyEvent to the next KeyEventDispatcher in the chain
    return false;

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 award (Website).

One Response to “How To Capture Key Events With JFrame or Window”

February 21, 2018 Reply

Thanks Albert Attard. Finally something that works on my frame for keyboard listening. It works but I need only single event and this fires the statements inside this function to fire up 3 times. Thanks again for the great start though. :)

Leave a Comment

Time limit is exhausted. Please reload the CAPTCHA.