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

你说的曾经没有我的故事 提交于 2019-12-06 23:14:27

问题


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?


回答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.




回答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.




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




回答4:


Use this code:

public void jTextField6KeyReleased(java.awt.event.KeyEvent evt)
{
    System.out.println(jTextField6.getText().length());
}


来源:https://stackoverflow.com/questions/401598/how-can-i-get-the-length-of-a-jtextfields-contents-as-the-user-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!