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.