Reputation: 2499
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
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
Reputation: 47608
Upvotes: 2