tags:

views:

483

answers:

3

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?

+4  A: 

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.

Sean Bright
+1  A: 

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.

VonC
+1  A: 

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).

Tom Hawtin - tackline