event

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();

  jButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("L"),

    act.getValue(AnAction.NAME));
    }
}

class AnAction extends AbstractAction {

    public AnAction() {

  super("my action");
    }

    @Override
    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.

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.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button