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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ariyan
  • 14,760
  • 31
  • 112
  • 175

3 Answers3

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);
haferblues
  • 2,155
  • 4
  • 26
  • 39
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()));
javanna
  • 59,145
  • 14
  • 144
  • 125
  • 1
    `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). – Thomas Mar 18 '11 at 11:20
  • 1
    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`. – user149408 Sep 05 '15 at 22:50
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);
}
Thomas
  • 87,414
  • 12
  • 119
  • 157