Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Automatically Scroll To a specific area in a JTextPane

 
Atrus Greyor
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have a bunch of text in a JTextPane, and I have a particular word that is being focused on (kinda like a spell checker would), how would accomplish something like this with a JScrollPane?
 
Rob Camick
Ranch Hand
Posts: 2612
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You scroll using the scrollRectToVisible() method.

You can get the Rectangle using the modelToView() method.
 
Atrus Greyor
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It doesn't seem to work. I tried to enter in the position of the caret (which is right before the word I want to have focused) as the argument for modelToView(), however upon running, nothing changed. I then tried entering various arbitrary values in, all to no effect. What exactly am I missing?

Code is as follows:
As a small bit of explanation, the word that I want focus on is ex2. ex1 contains a large amount of text, enough to put ex2 off screen, but I deleted it for shortness.
 
Rob Camick
Ranch Hand
Posts: 2612
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The viewport will only scroll when the rectangle is not in the current view. So create a simple test with 10 lines of data and set the viewport size to only display 3-4 lines of data. Then calculate the start of line 5-6 and attempt to force the viewport to scroll.

If you need further help then you need to create a SSCCE (Short, Self Contained, Compilable and Executable, Example Program), that demonstrates the incorrect behaviour.


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic