0

使用 JEditorPane,有没有办法判断插入符号当前是否在最后一行?我在 API 中找不到任何东西,或者更重要的是,在派生 JEditorPane 的 JTextComponent 中找不到任何东西。当用户使用向下箭头键向下移动文本时,我需要找出这一点。我目前的想法是这样的:

private boolean isEndOfText() {
  int tmpCurrent = editor.getCaretPosition();

  editor.getActionMap().get(DefaultEditorKit.endLineAction).actionPerformed(null);
  int tmpEnd = editor.getCaretPosition();
  try { editor.setCaretPosition(tmpEnd + 1); } catch (Exception e) { editor.setCaretPosition(tmpCurrent); return true; }
  editor.setCaretPosition(tmpCurrent);
  return false;
}

此代码将在按下向下键时运行,并通过检测是否发生错误来返回它是否实际上是文本的结尾,如果插入符号被放在最后可能的位置(即行尾)之后(如果它实际上是最后一行)否则意味着尚未到达文本的结尾。

4

2 回答 2

1

您应该能够使用Text Utilities。一种方法返回总行数,另一种方法返回插入符号处的行。

因为我不喜欢它的 HTML 支持,所以我从来没有这么多地使用过 JEditorPane。您还可以使用 editor.getDocument().getLength() 来确定插入符号是否位于文档的末尾。这适用于仅显示文本而不显示 HTML 的 JTextArea 或 JTextPane。不确定它在 JEditorPane 中是如何工作的。

于 2010-11-09T02:33:49.400 回答
0

可能有更好的方法,但你可以试试这个:

return editor.getText().indexOf("\n", editor.getCaretPosition()) == -1;
于 2010-11-08T22:20:21.530 回答