Ilya Ivanov
Ilya Ivanov

Reputation: 2499

Moving caret in JTextField using PlainDocument

I'm writing a custom control, based on JTextField. My JTextField uses my own Document class, derived from PlainDocument, so that I can process all the user input in overriden insertString(...) and remove(...) methods.

Here's the problem. After I process user input, sometimes I want to move the caret to another position. What is the better way to do it?

By default Document puts the caret next to last input. So I tried to put a char to my target position and delete it immediately. For some reason it doesn't work in remove() method... and the code doesn't look nice :)

Thanks for and proposals.

Upvotes: 4

Views: 1631

Answers (2)

Brian
Brian

Reputation: 17309

You should actually be using a DocumentFilter if you want to control user input. A DocumentFilter allows you to intercept all the input as it happens. You can then use JTextField.setCaretPosition (comes from JTextComponent) to set the caret position. Just pass your DocumentFilter implementation a reference to the JTextField so it can set the caret position for you.

Here's the Java trail for DocumentFilter. Also, an example on JavaRanch.

Upvotes: 2

Guillaume Polet
Guillaume Polet

Reputation: 47608

  • It seems unnecessary to extend PlainDocument. Simply add a DocumentListener to the Document of your JTextField and you can process the user input in the 3 methods declared in DocumentListener
  • Use setCaretPosition to move the caret to wherever you would like

Upvotes: 2

Related Questions