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

17,022

Solution 1

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.

Solution 2

This may be related to this "bug" (or rather "feature")

The listeners are notified of the key events prior to processing them to allow the listeners to "steal" the events by consuming them. This gives compatibility with the older awt notion of consuming events.
The "typed" event does not mean text was entered into the component. This is NOT a bug, it is intended behavior.

A possible solution is to listen to an associated Document

// Listen for changes in the text
myTextField.getDocument().addDocumentListener(new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
  // text was changed
}
public void removeUpdate(DocumentEvent e) {
  // text was deleted
}
public void insertUpdate(DocumentEvent e) {
  // text was inserted
}
});

Note this works no matter how the text gets changed; via a clipboard cut/paste, progamatic "setText()" on the TextField, or the user typing into the field on the UI.

Solution 3

KeyEvents are low-level events that are not appropriate here [that sounds familiar].

How does the JTextField system know that a character has been typed? Through a key typed event (IIRC, done through the PL&F). Does the event get dispatched to the system listener before your listener? It might or might not do.

In this case, you probably want to go to the Document and add a higher-level listener. With Swing it's a good idea to go for the model early - the 'J' class interfaces are incoherent. If you are intercepting input data, then you probably want a custom model (or in the case of Document a DocumentFilter).

Solution 4

Use this code:

public void jTextField6KeyReleased(java.awt.event.KeyEvent evt)
{
    System.out.println(jTextField6.getText().length());
}
Share:
17,022
Allain Lalonde
Author by

Allain Lalonde

I'm a Software Developer working on Alternative User Interfaces for business projects. I love working on things that make you "Why?".

Updated on June 18, 2022

Comments

  • Allain Lalonde
    Allain Lalonde almost 2 years

    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?