Elliott
Elliott

Reputation: 5609

Getting the visible text in a JEditorPane

I have a JeditorPane in a JScrollPane. At certain points in the application, I would like to retrieve the text that is visible in the scrollPane (the text that is currently showing) and only this text. Is there a way to do this?

Thank you,

Elliott

Upvotes: 1

Views: 1688

Answers (1)

camickr
camickr

Reputation: 324197

You can use the viewport to get the view position and size.

JViewport viewport = scrollPane.getViewport();
Point startPoint = viewport.getViewPosition();
Dimension size = viewport.getExtentSize();
Point endPoint = new Point(startPoint.x + size.width, startPoint.y + size.height);

Once you know the start/end points of the viewport you can use:

int start = editorPane.viewToModel( startPoint );
int end = editorPane.viewToModel( endPoint );

Once you know the offsets of the text you want you can get the text from the component:

String text = editorPane.getText(start, end - start);

None of the code is tested.

Upvotes: 7

Related Questions