I am currently creating a small jump and run in Java. I recently wanted to switch from a KeyListener to a Inputmap because the KeyListener seemed unresponsive at times.
I have a custom JFrame named Window with a JPanel and the following code:
public class EditorGamePanel extends JPanel {
Window parent;
MainGame maingame;
public EditorGamePanel(Window parent) {
this.parent = parent;
setLayout(null);
Canvas canvas = new MainGame(parent);
canvas.setBounds(0, 0, 1920, 1080);
add(canvas);
maingame = (MainGame) canvas;
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, 0, false), "pressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, 0, true), "released");
am.put("pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Pressed");
}
});
am.put("released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("released");
}
});
}
}
The problem is that it does not register me pressing Shift but it DOES register me letting go of Shift. Other keys like w seem to work just fine both ways. I cant seem to find any error or any help in the documentation.
You may be using the wrong KeyStroke for the shift-down key stroke. Instead of:
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, 0, false), "pressed");
try:
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, InputEvent.SHIFT_DOWN_MASK, false), "pressed");
Since this key stroke is not valid if the mask is set to 0.