我正在使用的程序具有JTextPane
,该程序包含用户可以编辑的大文档,并且该文档具有链接,以便一个人可以跳转到文档的不同部分(基本上,我正在尝试JTextPane
版本HTML [a href =“#link”]代码的形式)。现在,该代码几乎可以正常工作,当用户选择链接时,可以将插入符号正确地移动到正确的行。但是,无论我做什么,最后一个链接总是抛出IllegalArguementException
,表示我的位置为-1。我不知道为什么它一直这么说。
这是我的代码:
//JTextPane editor is instantiated above.
//searchTerm is the string that we are linking to in the text.
//I want the caret to move to where this text is in the JTextPane.
try
{
int textPosition = text.indexOf(searchTerm);
editor.setCaretPosition(textPosition);
Rectangle bottom = editor.modelToView(textPosition);
editor.scrollRectToVisible(bottom);
editor.grabFocus();
}
catch (BadLocationException | IOException ex) {
System.err.println("Could not scroll to " + ex);
ex.printStackTrace();
}
我已经检查过“文本”是否为纯文本格式(未设置样式)。那我在这里想念什么?任何帮助将不胜感激!
最佳答案
您不需要使用scrollRectToVisible或grabFocus方法。使用setCaretPosition()方法时,文本窗格应自动滚动。有关更多信息,请参见Text Area Scrolling。
如果您仍然对这种方法有疑问,请发布适当的SSCCE来说明问题。
也许Text Utilities中的centerLineInScrollPane(...)
方法是滚动的更好选择,因为文本将位于中心而不是底部。