I've been programming Java at a sub-professional level for 6 or 7 years now, and I've managed to bull my way through most problems, but this one has me stumped. I have a JScrollPane with a JTextPane as its child, declared as such:
Its purpose is simply to present a bunch of text. My problem is that, when mainScrollPane is drawn, and the length of the text exceeds the height of mainScrollPane, it presents the text with the scroll bar all the way down. That is to say, the top left corner of mainScrollPane does not show the beginning of the text; instead, the bottom right corner shows the end of the text. Obviously, this is wrong, and I'm surprised at this behavior; it certainly seems to violate normal UI expectations.
So I poked around and found setViewPosition, which is obviously designed to handle any problem like this. So I added this line of code to my window drawing method, immediately after the line that fills mainTextPane with text:
mainTextPane.setText(thisPage.mainText); // fill the JTextPane with the appropriate text
mainScrollPane.getViewport().setViewPosition(new Point(0,0)); // scroll to the top of the text
Much to my surprise, it didn't work. So I started digging around on various Java help websites, and found some other possibilities. I ended up trying all of these possibilities:
No joy. So I scoured the Internet, looking for discussions of JScrollPane and setViewPosition. There were lots of discussions about this from five or ten years ago, but nothing recent -- apparently everybody in the universe except me has figured this out.
I have noticed something that may include the key to my problem: it seems that the window is drawn once correctly and then immediately redrawn incorrectly. I say this because I can just barely sense that the text is jerking upward when first drawn. Perhaps some Listener somewhere is firing an even that tells mainScrollPane to scroll down. I tried moving this line to the bottom of the window drawing method:
Ta-Da! Huzzah and Halleluia! That fixed it! Specifically, Rob Camick's article discusses the idea of the Caret position. Even though I set up my mainTextPane as editable=false, Java automatically sets the caret to the end of the text, then autoscrolls to the caret. By setting the DefaultCaret's UpdatePolicy to NEVER_UPDATE, the bad behavior stopped. My problem is solved!