How can I get the length of a JTextField's contents as the user types?

Allain Lalonde picture Allain Lalonde · Dec 30, 2008 · Viewed 15.8k times · Source

JTextField has a keyTyped event but it seems that at the time it fires the contents of the cell have not yet changed.

Because of that .length() is always wrong if read here.

There must be a simple way of getting the length as it appears to the user after a key stroke?

Answer

Sean Bright picture Sean Bright · Dec 30, 2008

This is probably not the optimal way (and it's been a while), but in the past, I have added a DocumentListener to the JTextField and on any of the events (insert, update, remove) I:

evt.getDocument().getLength()

Which returns the total length of text field's contents.