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?
addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { if (txtGuess. getText(). length() >= 3 ) // limit textfield to 3 characters e.
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.
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();
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With