1

In an application with Java Swing components I have a JTextPane inside a non-editable JScrollPane, and some other fields where the user can enter some criteria. If the user clicks a certain button or menu item, there will be a search for a section of the document in the JTextPane that meets the given criteria, and if a match is found the section will be highlighted.

That part is solved; I can find the relevant document segment, know where it starts and ends (in terms of integer offsets), and highlight it.

But that highlighted segment might have scrolled off the screen and I need it to be scrolled to within the visible piece of the JScrollPane. I see there is a method scrollRectToVisible(Rectangle) on JComponent that seems like it might to do the job, but I don't see how to convert from the textual document position integer to a Rectangle.

Note that it is a non-editable JTextPane and I don't want to move the cursor the highlighted segment (the user cannot see the cursor anyway), I only want to make the segment show within the visible area of the JScrollPane.

Gigatron
  • 1,995
  • 6
  • 20
  • 27
  • Hadn't you heard of [modelToView(...)](http://docs.oracle.com/javase/7/docs/api/javax/swing/plaf/TextUI.html#modelToView(javax.swing.text.JTextComponent, int)) and viewToModel(...), methods. Seems like they are suitable for this case referred by you. Have a look at this [example](http://stackoverflow.com/questions/10462725/actionlistener-for-a-specific-text-inside-a-jtextarea/10463120#10463120) for more info. – nIcE cOw Jul 02 '12 at 17:40
  • ModelToView looks good! I'll try it later today. Please rewrite your comment as a separate answer so I can accept it if it works. – Gigatron Jul 02 '12 at 17:59

2 Answers2

2

Well you can use modelToView(...), that can return one Rectangle Object, that you can use for your case.

Here is one example by @camickr regarding the same

One more Example here

Community
  • 1
  • 1
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
  • That first link to `TextUI` seemed irrelevant, as it looks like that class is for writing a pluggable look and feel, and I don't see how I would use it for this purpose. However, the other examples used `modelToView` on the text component itself, and their technique worked. – Gigatron Jul 06 '12 at 02:14
  • It's hard to put this link alone for me in comments, actually it's the Class `TextUI` which has these methods `modelToView(...) and viewToModel(...)`, to give you one idea about the parameters of the method, that's why I had given those links :-) – nIcE cOw Jul 06 '12 at 04:42
0

If your text lines are the same height, then the y value of the Rectangle is document position * line height.

If your text lines are not the same height, then the y value of the Rectangle is the sum of the line heights up to but not including the document position.

The x value of the Rectangle would be zero, or some offset that makes sense for your text.

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111