Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep caret in TextArea when non-editable

I'm using java, and I'm trying to make a JTextArea that is non-editable but still has the caret in the field. In other words, a Text Area that does not display characters typed by the user, but still has the blinking caret (i.e. focus).

I honestly stumped on this problem. I've tried mucking around with setEditable, but theres no way to keep the caret. I've also tried deleting the character the user enters as soon as they type it, but i can't stop it flashing on the screen.

like image 754
Jarred Filmer Avatar asked Dec 19 '11 12:12

Jarred Filmer


2 Answers

I think the following will help you:

textArea.getCaret().setVisible(true);

or

textArea.getCaret().setSelectionVisible(true);
like image 68
Jomoos Avatar answered Sep 17 '22 18:09

Jomoos


As for the answers above

textArea.getCaret().setVisible(true);

does not always work perfectly, if the TextArea or EditorPane loses focus, say you click on a different frame or something, when you come back the cursor will be invisible again.

I have had the same issues, it appears the solution is to add a focus listener and set it visible every time the editor gains focus.

text.addFocusListener(new FocusAdapter() {
  @Override
  public void focusGained(FocusEvent e) {
    text.getCaret().setVisible(true); // show the caret anyway
  }
});
like image 22
Goombert Avatar answered Sep 20 '22 18:09

Goombert