Swing: how to discover the current character position on a JEditPane

Did you ever had the need to know your current character position on a JEditorPane? Well, I had to and, for my surprise, it wasn’s so simple as I thought. In a first moment, I thought: “hmm… probably there’s some method in this class like getCurrentCharacterLine() or getCurrentCharacterColumn() that I can use”. Well, that’s not the case.

So here is a little snippet you may use to solve this problem:


//txtScript is an instance of javax.swing.JEditorPane
txtScript.addCaretListener(

/*

In this case, I added a new intance of CaretListener so I could update the caption of a JLabel component with the current row and column of the cursor.

*/
txtScript.addCaretListener(
new CaretListener() {

public void caretUpdate(CaretEvent e) {

int row = txtScript.getDocument().getRootElements()[0].getElementIndex(txtScript.getCaretPosition());

int column = txtScript.getCaretPosition() - txtScript.getDocument().getRootElements()[0].getElement(row).getStartOffset();

lblCharacterPosition.setText("Row: " + (row + 1) + ", Column:" + (column + 1));

}

}

));


Publicado

em

, ,

por

Tags:

Comentários

Uma resposta para “Swing: how to discover the current character position on a JEditPane”

  1. […] Itexto.net blogs about finding the position of the character at the position of the carat in a JEditorPane. […]

Deixe uma resposta

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.