Disable scrolling to end of text in JEditorPane

Hi
I used JEditorPane with HTMLEditorKit to display HTML text with the ability to wrap text.
The problem is when I set its contents using the .setText method, it automatically scrolls to the end of this text.
How can I disable this?

Thank.

+3
source share
3 answers

You can try this trick to keep the cursor position in front setText()and then restore it as soon as you add text to the component:

int caretPosition = yourComponent.getCaretPosition();
yourComponent.setText(" your long text  ");
yourComponent.setCaretPosition(Math.min(caretPosition, text.length()));
+4
source

Try the following:

final DefaultCaret caret = (DefaultCaret) yourEditorPane.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
//!!!!text must be set AFTER update policy has been set!!!!!
yourEditorPane.setText(text);
+2
source

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);
}
+1
source

All Articles