Java Swing How to - Set the caret color for JTextArea








Question

We would like to know how to set the caret color for JTextArea.

Answer

//from  ww  w . j  av  a  2  s .  c  om
import java.awt.Color;

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

public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent c = new JTextArea();
    c.getCaretPosition();
    if (c.getCaretPosition() < c.getDocument().getLength()) {
      char ch = c.getText(c.getCaretPosition(), 1).charAt(0);
    }
    // Set the caret color
    c.setCaretColor(Color.red);
  }
}