Frage

Well, this is a small problem maybe, but I couldn't figure it.
I want my program display the text in current cursor position when I press the Enter key.
Here's my current code:

if (evt.getKeyCode() == 10) {
  try {
    int offset=ta.getLineOfOffset(ta.getCaretPosition());
    int start=ta.getLineStartOffset(offset);
    int end=ta.getLineEndOffset(offset);

    System.out.println("ext: "+ta.getText(start, end));

  } catch (BadLocationException ex) {
    System.out.println(ex.getMessage());
  }
}  

It works only for the first time I press the Enter key, the next time I press it, it throws an exception "Invalid Location".
Any better way to do this?

War es hilfreich?

Lösung

Hhehe, solved it by myself:

Here's the correct code for what I'm looking for:

if (evt.getKeyCode() == 10) {
  try {
    int offset=ta.getLineOfOffset(ta.getCaretPosition());
    int start=ta.getLineStartOffset(offset);
    int end=ta.getLineEndOffset(offset);

    System.out.println("Text: "+ta.getText(start, (end-start)));                
  } catch (BadLocationException ex) {
    System.out.println(ex.getMessage());
  }
}

Maybe it's useful to another guy out there :)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top