我正在开发一个程序,它有一个JTextPane
,它保存用户可以编辑的大文档,并且该文档具有链接,以便人们可以跳转到文档的不同部分(基本上我正在尝试 HTML [a href="#link"] 代码的 JTextPane
版本。现在,代码几乎可以工作,当用户选择链接时,可以将插入符号正确移动到正确的行。然而,无论我做什么,最后一个链接总是抛出一个 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() 方法时,文本 Pane 应该自动滚动。请参阅Text Area Scrolling了解更多信息。
如果您对这种方法仍然有问题,请发布正确的 SSCCE这说明了问题。
也许是 Text Utilities 中的 centerLineInScrollPane(...)
方法将是更好的滚动选项,因为文本将位于中心而不是底部。
关于Java - 向下滚动到 JTextPane 中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25093307/