I have a Game Window to which I am trying to put W, A, S and D as scroll keys for the JScrollPane. This is what I have done so far on the method that runs it. The JScrollPane is not local. When I run it, the program runs fine but, the keys don’t do anything. I tried it with putting a breakpoint inside the action, so that it would run when it was responding to a button push but it didn’t do anything.
I would appreciate any input, let me know if you need more information.
/**
* This sets all the key commands to the scroll pane for up, down, left, right.
* These are W, S, A, D
* It also sets the increment amount.
*/
private void setupScrollKeys()
{
//sets up the scroll panes unit increment.
final int increment = 80;
scrollPane.getHorizontalScrollBar().setUnitIncrement(increment);
scrollPane.getVerticalScrollBar().setUnitIncrement(increment);
//set all the keyStrokes for up, down, left, right on the scroll pane.
KeyStroke kUp = KeyStroke.getKeyStroke(KeyEvent.VK_W, 0);
KeyStroke kDown = KeyStroke.getKeyStroke(KeyEvent.VK_S, 0);
KeyStroke kLeft = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0);
KeyStroke kRight = KeyStroke.getKeyStroke(KeyEvent.VK_D, 0);
// set W for key up.
scrollPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
.put(kUp, "keyUp");
scrollPane.getActionMap().put("keyUp", new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
final JScrollBar bar = scrollPane.getVerticalScrollBar();
int currentValue = bar.getValue();
bar.setValue(currentValue - increment);
}
});
}
Try changing the line
to
I had no idea of key bindings, so I found this tutorial really handy.
How to Use Key Bindings