Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Scrolling JTextPane so cursor is at top of visible rectangle  RSS feed

 
Bill Stackhouse
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would like to set the cursor in a JTextPane that is within a JScrollPane then have it positioned to the top of the visible rectangle. The default behavior is to position it to the bottom. How can I reposition the visible rectangle the correct amount if I know the cursor position in the document?

Thanks
Bill
 
Brian Cole
Author
Ranch Hand
Posts: 947
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the behavior of the default caret may be more complicated than you describe. That said, it is controlled primarily by the text component's scrollRectToVisible() method and by the DefaultCaret's adjustVisibility() method, both of which can be overridden.

For example, you could try something simple like this:
Then install it by calling yourTextPane.setCaret( new MyCaret() ).

Note that one should be wary of threading issues in the adjustVisibility() method. For example, the code above calls getVisibleRect() without first checking that it's running on the Event Dispatch Thread, which probably isn't kosher.
 
Bill Stackhouse
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian Cole, thanks for the suggestion. it worked, but of course forced the action everytime the cursor was set. I only wanted it in certain cases. There was just enough to show me how to solve the problem.

 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!