Java JTextComponent Caret selectLineAtCaret(JTextComponent editor)

Here you can find the source of selectLineAtCaret(JTextComponent editor)

Description

select Line At Caret

License

Apache License

Declaration

public static void selectLineAtCaret(JTextComponent editor) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import javax.swing.text.JTextComponent;

public class Main {
    public static void selectLineAtCaret(JTextComponent editor) {
        int lineStart = getLineStart(editor.getText(), editor.getCaretPosition());
        int lineEnd = getLineEnd(editor.getText(), editor.getCaretPosition());
        if (lineEnd < editor.getText().length()) {
            lineEnd++;// w w w.  j  a  va  2s.  c  o m
        }
        editor.getCaret().setDot(lineEnd);
        editor.getCaret().moveDot(lineStart);
    }

    public static int getLineStart(String text, int initialCaretPosition) {
        int pos = Math.min(Math.max(0, initialCaretPosition), text.length());
        while (pos > 0) {
            if (text.charAt(pos - 1) == '\n') {
                break;
            }
            pos--;
        }
        return pos;
    }

    public static int getLineEnd(String text, int initialCaretPosition) {
        int pos = Math.min(Math.max(0, initialCaretPosition), text.length());
        while (pos < text.length()) {
            if (text.charAt(pos) == '\n') {
                break;
            }
            pos++;
        }
        return pos;
    }
}

Related

  1. getCaretCol(int idx, JTextComponent comp)
  2. getCaretRow(int idx, JTextComponent comp)
  3. getLineAtCaret(final JTextComponent component)
  4. makeCaretAlwaysVisible(final JTextComponent comp)
  5. setCaretUpdateEnabled(JTextComponent comp, boolean updateEnabled)
  6. setTextAndResetCaret(JTextComponent component, String text)