Java 禁用在窗格中滚动到文本结尾
你好Java 禁用在窗格中滚动到文本结尾,java,swing,scroll,jeditorpane,htmleditorkit,Java,Swing,Scroll,Jeditorpane,Htmleditorkit,你好 我使用带有HTMLEditorKit的JEditorPane来显示HTML文本,并能够包装文本。 问题是,当我使用.setText方法设置它的内容时,它会自动滚动到该文本的末尾。 如何禁用此功能 谢谢。您可以尝试此技巧,将光标位置保存在setText()之前,然后在将文本添加到组件后将其还原: int caretPosition = yourComponent.getCaretPosition(); yourComponent.setText(" your long text "); y
我使用带有HTMLEditorKit的JEditorPane来显示HTML文本,并能够包装文本。
问题是,当我使用.setText方法设置它的内容时,它会自动滚动到该文本的末尾。
如何禁用此功能
谢谢。您可以尝试此技巧,将光标位置保存在
setText()
之前,然后在将文本添加到组件后将其还原:
int caretPosition = yourComponent.getCaretPosition();
yourComponent.setText(" your long text ");
yourComponent.setCaretPosition(Math.min(caretPosition, text.length()));
在
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);
}
试试这个:
final DefaultCaret caret = (DefaultCaret) yourEditorPane.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
//!!!!text must be set AFTER update policy has been set!!!!!
yourEditorPane.setText(text);
yourComponent.setCaretPosition(Math.min(caretPosition,text.length())如果新文本比前一个短,则code>最好防止出现IllegalArgumentException
。要滚动到第一行:yourComponent.setCaretPosition(0)
,这实际上比我的答案更容易:)(+1)。但是请注意,当JEditorPane
为只读时,这可能会产生意外的结果:用户没有在此处设置插入符号位置,滚动可能会将插入符号移出视图。但是,setCaretPosition(0)
将按照只读JEditorPane
的预期工作。请参阅haferblues的答案,以了解将保留只读JEditorPane
位置的解决方案。这是将保留只读JEditorPane
位置的唯一答案。谢谢