Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

java - How to stop JScrollPane from auto scrolling to bottom on initial display?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay, I found a solution.

caption.setCaretPosition(0);

Like many programming problems, it's simple when you know how to do it.

I still don't understand why viewport.setLocation doesn't work. Elsewhere in the same program I use that exact same function to scroll the same text box. But whatever.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...