Reputation: 83
I'm about to use keybinding in a swing application for the num pad enter key, but the key is difficult to catch.
All examples I have seen rely on something like
key == KeyEvent.VK_KP_LEFT
where VK_KP_LEFT is some predefined value. Other options are to define a keystoke like this:
KeyStroke.getKeyStroke("control A");
KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK);
but I have not found the "modifier" for numpad.
What is easily to obtain is the difference between the general and the numpad-enter:
All numpad-keys (indepently if switched in the numeric mode or not) get assigned the
getKeyLocation() == 4
(I spottetd this from key pressed / key released methods)
The question is:
How to properly prepare the keyStroke for numpad enter key to use it in the
inputMap.put(KeyStroke keyStroke, Object actionMapKey)
key binding method?
Thanks,
Tarik
Upvotes: 0
Views: 5859
Reputation: 21223
If you're looking for binding Enter key you can use KeyEvent.VK_ENTER
, ie:
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "someAction");
getActionMap().put("someAction", someAction);
Here is a short example:
import java.awt.event.*;
import javax.swing.*;
public class Test {
public static void main(String[] args) throws Exception {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(new JLabel("Hit Enter"));
Action someAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Got it");
}
};
panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "someAction");
panel.getActionMap().put("someAction", someAction);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
EDIT: VK_ENTER on numeric pad vs main keyboard
After some testing, it looks like it may not be possible to bind these keys separately.
The same KeyStroke
is generated for both keys. The implementation of JComponent.processKeyBinding
does not examine the KeyEvent
, all it cares is KeyStroke
in order to find the desired action.
SwingUtilities.notifyAction
that is responsible for dispatching the actual action does not delegate all the details of the KeyEvent
(only key, modifiers and when). So inside action there is no way to distinguish either as there is no details in ActionEvent
.
If it worth the trouble, you can override processKeyBinding
and add some logic if needed. You can also use KeyboardFocusManageraddKeyEventDispatcher()
for blocking one of the keys.
Upvotes: 2
Reputation: 537
How about this?
if(keyEvent.getKeyLocation() == KeyEvent.KEY_LOCATION_NUMPAD
&& keyEvent.getKeyCode() == KeyEvent.VK_ENTER)
Upvotes: -1