event
Change active keystrokes
With this tutorial we shall show you how to change active keystrokes in a Java application. You might find this useful when you are developing an application that has rich and intense keyboard activity and you want to customize it to make it very flexible for each user dynamically to use his own keystrokes.
In short, to change active keystrokes in a Java Desktop Application, one should follow these steps:
- Use
KeyStroke.getKeyStroke
method to get a specific keyStroke. - Get the
InputMap
of aJButton
for instance InputMap.put(KeyStroke keystroke, ACTION_KEY)
method to add the keystroke to the button. Now every time the user hits the specifickeystroke
, the button will be pressed.
Let’s see the code snippet that follows:
package com.javacodegeeks.snippets.desktop; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.KeyStroke; public class Main { private static final String ACTION_KEY = "theAction"; public static void main(String args[]) { JFrame jFrame = new JFrame("KeyStroke Sample"); JButton b1 = new JButton("Press Control + alt + 7"); JButton b2 = new JButton("Press Enter"); JButton b3 = new JButton("Press F4 + Shift"); JButton b4 = new JButton("Press Space Bar"); Action actListner = new AbstractAction() { @Override public void actionPerformed(ActionEvent actionEvent) { JButton srcButton = (JButton) actionEvent.getSource(); System.out.println("Recived keyStroke: " + srcButton.getText()); } }; KeyStroke ctrl = KeyStroke.getKeyStroke("control alt 7"); InputMap inputMap = b1.getInputMap(); inputMap.put(ctrl, ACTION_KEY); ActionMap actionMap = b1.getActionMap(); actionMap.put(ACTION_KEY, actListner); KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true); inputMap = b2.getInputMap(); inputMap.put(enter, ACTION_KEY); b2.setActionMap(actionMap); KeyStroke shiftF4 = KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.SHIFT_MASK); inputMap = b3.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); inputMap.put(shiftF4, ACTION_KEY); b3.setActionMap(actionMap); KeyStroke space = KeyStroke.getKeyStroke(' '); inputMap = b4.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(space, ACTION_KEY); b4.setActionMap(actionMap); Container contentPane = jFrame.getContentPane(); contentPane.setLayout(new GridLayout(2, 2)); contentPane.add(b1); contentPane.add(b2); contentPane.add(b3); contentPane.add(b4); jFrame.setSize(800, 600); jFrame.setVisible(true); } }
This was an example on how to change active keystrokes in a Java Application.