Moving the Caret of a JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Moving the Caret of a JTextComponent

Demo Code

import java.awt.Color;

import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;

public class Main {
  public void main(String[] argv) {
    JTextComponent c = new JTextArea();
    if (c.getCaretPosition() < c.getDocument().getLength()) {
      try {//  w ww .  jav  a  2s .com
        char ch = c.getText(c.getCaretPosition(), 1).charAt(0);
      } catch (BadLocationException e) {
      }
    }

    // Move the caret
    int newPosition = 0;
    c.moveCaretPosition(newPosition);

    // Set the caret color
    c.setCaretColor(Color.red);
  }
}

Related Tutorials