JEdi​​torPane 是最后一行

发布于 2024-10-01 09:54:42 字数 657 浏览 1 评论 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;
}

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

Using a JEditorPane, is there any way to tell if the caret is currently on the last line? I cannot find anything in the API or more importantly JTextComponent of which JEditorPane is derived. I need to find this out when the user uses the down arrow key to move down the text. My current idea is this:

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;
}

This code would run whenever the down key is pressed and would return whether or not it is in fact the end of the text by detecting if an error occurs if the caret is being put after the last possible position which would be the end of the line (if it is in fact the last line) otherwise it means the end of text has not been reached.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

街道布景 2024-10-08 09:54:42

您应该能够使用文本实用程序。一种方法返回总行数,另一种方法返回插入符号处的行。

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

You should be able to use the Text Utilities. One method returns the total lines and another method return the line at the caret.

I've never played with a JEditorPane that much since I don't like its HTML support. You might also be able to use editor.getDocument().getLength() to determine if the caret is at the end of the document. This will work with a JTextArea or a JTextPane that only displays text, not HTML. Not sure how it works in a JEditorPane.

野心澎湃 2024-10-08 09:54:42

可能有更好的方法,但你可以尝试一下:

return editor.getText().indexOf("\n", editor.getCaretPosition()) == -1;

There's probably a better way, but you could try this:

return editor.getText().indexOf("\n", editor.getCaretPosition()) == -1;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文