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)); } } ));
Pingback: Java desktop links of the week, August 30 | Jonathan Giles