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?
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.
JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With