Disabling scrolling to end of text in JEditorPane
Asked Answered
V

3

6

Hi
I used a JEditorPane with HTMLEditorKit to showing HTML text with ability to wrap text.
The problem is when I set it's content using .setText method it automatically scrolls to the end of that text.
How can I disable this?

Thanks.

Vesica answered 18/3, 2011 at 10:31 Comment(0)
I
5

You can try this trick to save the cursor position before the setText() and then restore it once you've added your text to the component:

int caretPosition = yourComponent.getCaretPosition();
yourComponent.setText(" your long text  ");
yourComponent.setCaretPosition(Math.min(caretPosition, text.length()));
Institutionalize answered 18/3, 2011 at 10:42 Comment(2)
yourComponent.setCaretPosition(Math.min(caretPosition, text.length())); would be better to prevent IllegalArgumentException if the new text is shorter than the previous. To scroll to the first line: yourComponent.setCaretPosition(0) which would actually be easier than my answer :) (+1).Eros
Do note, however, that this may produce unexpected results when the JEditorPane is read-only: the user does not set the caret position here, and scrolling may move the caret out of view. However, setCaretPosition(0) will work as expected for a read-only JEditorPane. See haferblues's answer for a solution that will preserve the position for a read-only JEditorPane.Warmup
A
5

Try this:

final DefaultCaret caret = (DefaultCaret) yourEditorPane.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
//!!!!text must be set AFTER update policy has been set!!!!!
yourEditorPane.setText(text);
Affected answered 20/2, 2013 at 13:2 Comment(1)
This is the only answer which will preserve the position for a read-only JEditorPane. Thanks!Warmup
E
1

Try this after setText:

Rectangle r = modelToView(0); //scroll to position 0, i.e. top
if (r != null) {
  Rectangle vis = getVisibleRect(); //to get the actual height
  r.height = vis.height;
  scrollRectToVisible(r);
}
Eros answered 18/3, 2011 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.