Moving a cursor in a JTextField using PlainDocument

I am writing a user control based on JTextField. My JTextField uses my own Document class, derived from PlainDocument, so that I can handle all user input in the redefined methods of insertString(...) and remove(...) .

Here is the problem. After processing user input, sometimes I want to move the cursor to another position. What is the best way to do this?

By default, the document places a caret next to the last entry. So I tried to put the char at my target position and immediately delete it. For some reason, it does not work in the remove() method ... and the code does not look very good :)

Thanks for and suggestions.

+4
source share
2 answers
  • No need to distribute PlainDocument. Just add a DocumentListener to your JTextField document and you can handle user input in 3 methods declared in the DocumentListener
  • Use setCaretPosition to move the caret to where you would like
+2
source

In fact, you should use DocumentFilter if you want to control user input. A DocumentFilter allows you to intercept all input when this happens. Then you can use JTextField.setCaretPosition (from JTextComponent ) to set the caret position. Just pass the DocumentFilter implementation a reference to the JTextField so that it can set the caret position for you.

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

+2
source

Source: https://habr.com/ru/post/1435940/


All Articles