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


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.

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




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

  1. Pingback: Java desktop links of the week, August 30 | Jonathan Giles

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

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