Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 802
Allain Lalonde Avatar asked Dec 30 '08 21:12

Allain Lalonde


People also ask

How do I limit the number of characters in a JTextField?

addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { if (txtGuess. getText(). length() >= 3 ) // limit textfield to 3 characters e.

What is JTextField in Java?

JTextField is a lightweight component that allows the editing of a single line of text. For information on and examples of using text fields, see How to Use Text Fields in The Java Tutorial. JTextField is intended to be source-compatible with java. awt. TextField where it is reasonable to do so.

How do I add a text field to a JFrame?

You need to create an instance of the JTextField class and add it to your panel and JFrame. Creating a new text field is the same as instantiating any object. The code here creates the JFrame, adds a label, and then adds a text field for the user to enter some information: JTextField textField = new JTextField();

How do I get text in Java?

GetText returns the text from the single-line text field. It returns only the first line of a multi-line text field. If you include iStartChar but not iNumChars , GetText returns the text from the iStartChar character to the end of the text.


2 Answers

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.

like image 180
Sean Bright Avatar answered Sep 30 '22 02:09

Sean Bright


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.

like image 45
VonC Avatar answered Sep 30 '22 02:09

VonC