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.
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.
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()));
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 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);
JEditorPane
. Thanks! –
Warmup 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);
}
© 2022 - 2024 — McMap. All rights reserved.
yourComponent.setCaretPosition(Math.min(caretPosition, text.length()));
would be better to preventIllegalArgumentException
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