JScrollPane scrolling with arrow keys

JooMing picture JooMing · Nov 28, 2010 · Viewed 10k times · Source

I've a JTextArea component inside JScrollPane and the text area is not editable. I would like to enable scrolling of the text area with up and down arrow keys (i.e. pressing the arrow keys will scroll the text area by one line). Any ideas how to achieve this?

Answer

camickr picture camickr · Nov 29, 2010

Yes Key Bindings is the way to go, but you don't always need to create your own actions. Swing components come with default Actions that you can often reuse.

See Key Bindings for a complete list of these Actions.

Now that you know the Action name you can just bind it to a keyStroke:

JScrollBar vertical = scrollPane.getVerticalScrollBar();
InputMap im = vertical.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke("DOWN"), "positiveUnitIncrement");
im.put(KeyStroke.getKeyStroke("UP"), "negativeUnitIncrement");