Articles Projects Tips Downloads Contacts About

Row and column number for current caret position.

The code below can be used to with JTextArea as well as JEditorPane and JTextPane. The javax.swing.text.Utilities class provides a method to get row start for model position. A small extension of the method allows to get row and column numbers

    public static int getRow(int pos, JTextComponent editor) {
        int rn = (pos==0) ? 1 : 0;
        try {
            int offs=pos;
            while( offs>0) {
                offs=Utilities.getRowStart(editor, offs)-1;
                rn++;
            }
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        return rn;
    }

    public static int getColumn(int pos, JTextComponent editor) {
        try {
            return pos-Utilities.getRowStart(editor, pos)+1;
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
        return -1;
    }

And how to use the methods

   myJTextComponent.addCaretListener(new CaretListener() {
       public void caretUpdate(CaretEvent e) {
           System.out.println("row="+getRow(e.getDot(), (JTextComponent)e.getSource()));
           System.out.println("col="+getColumn(e.getDot(), (JTextComponent)e.getSource()));
       }
   });