Home » Desktop Java » awt » event » Activate a Keystroke when the window has focus

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Activate a Keystroke when the window has focus

With this tutorial we shall show you how to activate a Keystroke when on of the window of out application gains focus.

This is very simple and to do it you have to follows these steps:

  • Create a class that extends AbstractAction. You can bind this action with a certain keystroke if you want.
  • Create an input device like a JButton.
  • Use getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) to set up the keystroke you want when a window gains focus.

Let’s see the code that follows:

package com.javacodegeeks.snippets.desktop;

import java.awt.event.ActionEvent;
import javax.swing.*;

public class Main {

    public static void main(String[] argv) throws Exception {

  JButton jButton = new JButton("Button");

  AnAction act = new AnAction();



class AnAction extends AbstractAction {

    public AnAction() {

  super("my action");

    public void actionPerformed(ActionEvent e) {

  System.out.println("Action performed succesfully");


This was an example on how to activate a keystroke when the window has focus.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of