Code example for JTextComponent

Methods: addCaretListenergetCaretPositiongetDocumentgetSelectionEndgetSelectionStart

0
    private String selectionFormat = "%d:%d - %d:%d (%d)";
 
    public CaretMonitor(JTextComponent text, JLabel label) {
        this.label = label;
        this.text = text;
        text.addCaretListener(this);
		updateLabel(text.getCaretPosition());
    } 
 
    @Override 
    public void caretUpdate(CaretEvent evt) {
		updateLabel(evt.getDot());
	} 
 
	protected void updateLabel(int pos) {
        if (text.getDocument() instanceof SyntaxDocument) {
            try { 
                if (text.getSelectionStart() == text.getSelectionEnd()) {
                    String loc = String.format(noSelectionFormat,
                            ActionUtils.getLineNumber(text, pos) + 1,
                            ActionUtils.getColumnNumber(text, pos) + 1,
                            pos);
                    label.setText(loc);
                } else { 
                    int start = text.getSelectionStart();
                    int end = text.getSelectionEnd();
                    String loc = String.format(selectionFormat,
                            ActionUtils.getLineNumber(text, start) + 1,
                            ActionUtils.getColumnNumber(text, start) + 1,
                            ActionUtils.getLineNumber(text, end) + 1,
                            ActionUtils.getColumnNumber(text, end) + 1,
                            (end - start),
                            start,
                            end);
                    label.setText(loc);
                }