By Alvin Alexander. Last updated: June 6, 2016
If you want to set your Java JScrollPane scrollbars to always scroll, both horizontally and vertically, this code shows the solution:
private JScrollPane createNewScrollPaneWithEditor(JTextArea textArea) {
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getViewport().add(textArea);
scrollPane.getViewport().setPreferredSize(textArea.getPreferredSize());
return scrollPane;
}
The two important lines of code that makes the JScrollPane always show the scrollbars are these:
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
This example shows a JTextArea, but the scrollpane should work regardless of which Swing component it contains.

