I have a JFrame with a JScrollPane containing a JTextArea. The scrollpane is configured to never show the horizontal scrollbar, and show the vertical scrollbar as needed. As the text in the text area grows the vertical scrollbar eventually appears, hiding part of the text area. I would expect the scrollbar to resize its content as needed when the scrollbar appears.
One workaround I've found is to always display the vertical scrollbar, but that doesn't look good, as it's rarely needed.
The below code snippet reproduces the problem after enough text is entered on my system (Windows 10)
import javax.swing.*;
import java.awt.*;
import static javax.swing.ScrollPaneConstants.*;
public class Test {
public static void main(String[] args) {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new JLabel("text"));
panel.add(new JLabel("text"));
panel.add(new JLabel("text"));
JTextArea textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setText("This text fits");
panel.add(textArea);
JScrollPane scrollPane =
new JScrollPane(panel, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER);
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollPane);
frame.pack();
frame.setVisible(true);
}
}
I would expect the scrollbar to resize its content as needed when the scrollbar appears.- that is not what a scrollpane does. As the size of the components added to the scrollpane increase the scrollbar appears. Therefore you can then use the scrollbar to scroll the components up/down in the scrollpane to see all the components. I suspect that you really only want the scrollbar on the text area to that all the components are visible and then text in the text area scrolls as you add more text. - camickr