Java Utililty Methods JTextComponent Caret

List of utility methods to do JTextComponent Caret

Description

The list of methods to do JTextComponent Caret are organized into topic(s).

Method

intgetCaretCol(int idx, JTextComponent comp)
Method getCaretCol.
return Math.abs(Utilities.getRowStart(comp, idx) - idx);
intgetCaretRow(int idx, JTextComponent comp)
Method getCaretRow.
return getLineOfOffset(idx, comp.getDocument());
intgetLineAtCaret(final JTextComponent component)
get Line At Caret
final int caretPosition = component.getCaretPosition();
final Element root = component.getDocument().getDefaultRootElement();
return root.getElementIndex(caretPosition) + 1;
FocusListenermakeCaretAlwaysVisible(final JTextComponent comp)
Make caret visible even when the JTextComponent is not editable.
FocusListener listener = new FocusAdapter() {
    @Override
    public void focusGained(FocusEvent e) {
        Caret caret = comp.getCaret();
        caret.setVisible(true);
        caret.setSelectionVisible(true);
};
...
voidselectLineAtCaret(JTextComponent editor)
select Line At Caret
int lineStart = getLineStart(editor.getText(), editor.getCaretPosition());
int lineEnd = getLineEnd(editor.getText(), editor.getCaretPosition());
if (lineEnd < editor.getText().length()) {
    lineEnd++;
editor.getCaret().setDot(lineEnd);
editor.getCaret().moveDot(lineStart);
voidsetCaretUpdateEnabled(JTextComponent comp, boolean updateEnabled)
set Caret Update Enabled
Caret caret = comp.getCaret();
if (caret instanceof DefaultCaret) {
    ((DefaultCaret) caret)
            .setUpdatePolicy(updateEnabled ? DefaultCaret.UPDATE_WHEN_ON_EDT : DefaultCaret.NEVER_UPDATE);
voidsetTextAndResetCaret(JTextComponent component, String text)
set Text And Reset Caret
component.setText(text);
component.setCaretPosition(0);