Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JScrollPane scrolling with arrow keys

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?

like image 498
JooMing Avatar asked Nov 28 '10 19:11

JooMing


People also ask

What is the difference between a scrollbar and a JScrollPane?

A JSrollPane is used to make a scrollable view of a component. A scroll pane is an object of the JScrollPane class which extends JComponent class. When screen size is limited, we use a scroll pane to display a large component or a component whose size can change dynamically.

Is JList scrollable?

JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane.


1 Answers

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");
like image 188
camickr Avatar answered Oct 16 '22 22:10

camickr