user372743
user372743

Reputation:

JEditorPane Is Last Line

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.

Upvotes: 0

Views: 907

Answers (2)

camickr
camickr

Reputation: 324147

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.

Upvotes: 1

lins314159
lins314159

Reputation: 2520

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

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

Upvotes: 0

Related Questions