Gigatron
Gigatron

Reputation: 2055

How to scroll to a given position in a document displayed in a JScrollPane

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.

Upvotes: 1

Views: 150

Answers (2)

nIcE cOw
nIcE cOw

Reputation: 24626

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

Upvotes: 2

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

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.

Upvotes: 0

Related Questions