I have a JScrollPane wrapped around a JTextArea. When I populate the JTextArea, it automatically scrolls to the bottom. I want it to be at the top.
Here's the code that creates them:
caption=new JTextArea();
caption.setLineWrap(true);
caption.setWrapStyleWord(true);
scrollCaption=new JScrollPane(caption);
scrollCaption.setPreferredSize(new Dimension(180,20));
scrollCaption.setMinimumSize(new Dimension(100,20));
And here's the code that populates it:
int fontsize=scrollCaption.getHeight()/4;
if (fontsize<10) fontsize=10;
caption.setFont(caption.getFont().deriveFont((float)fontsize));
String path=textfile.getAbsolutePath();
List<String> lines=Files.readAllLines(Paths.get(path));
StringBuilder sb=new StringBuilder();
for (String line : lines)
{
sb.append(line).append('
');
}
caption.setText(sb.toString());
int scrollmax=scrollCaption.getVerticalScrollBar().getMaximum();
// scrollCaption.getVerticalScrollBar().setValue(0);
scrollCaption.getViewport().setViewPosition(new Point(0,0));
I tried saying getVerticalScrollBar().setValue(0) and it still scrolled to the bottom. Then I tried getViewPort.setViewPosition(new Point(0,0)) and it still scrolled to the bottom. Maybe I'm doing these too soon? That there's some sort of "autoscroll to bottom" that's happening after I do this? But I don't know when else I could catch it.
One other clue: If I scroll to the top, and then resize the window, it stays scrolled to the top.
I'm running in Java 8.
question from:
https://stackoverflow.com/questions/65878230/how-to-stop-jscrollpane-from-auto-scrolling-to-bottom-on-initial-display 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…