In TextField, we need to set its input length, but what about it? There is no specific method in Java, so you have to write one yourself.
The first method is given here first:
For the TextField object, add an event listener to it, each time you type a character from the keyboard, judge its length, and if the length reaches a certain condition, you cannot continue the input (implemented by the consume method).
public void keytyped (KeyEvent e) {//TODO auto-generated method stubstring s = Textfield.gettext (); if (S.length () >= 8) E.consume ();}
after testing, calling the consume method in the Keyreleased method and the Keypressed method does not implement the effect.
Let's introduce this consume method, which is used to destroy the instance. In the above code, when the length of S is greater than or equal to 8 o'clock, the extra characters are destroyed, thus the effect of limiting the input length is reached.
I tested it, and when I pressed a button, I first called the keypressed method, and then I displayed the typed character in the TextField text box, and then called the Keyreleased method.
That is, if I call the consume method in keypressed, it will not be able to limit the effect of the character input length, because the characters in the text box are displayed after I have finished the Keypressed method.
Similarly, why not in the keyrelease? I think so (do not know right), after calling Keypressed, the character immediately appears in the text box, but at this time has not yet called the keyreleased method, so the same can not be achieved by the consume method to limit the effect of the input length.
All of these are personal views, as for the right I do not know, I Baidu for a long time also did not find this information.
Then the second method:
There is also a class object that inherits Plaindocument by calling the Setdocument method, and overrides the Insertstring method in the class, with the following code:
public class Jtextfieldlimit extends plaindocument {private int limit; Limit the length of public jtextfieldlimit (int limit) {super ();//Call the parent class construct this.limit = limit;} public void insertstring (int offset, String str, AttributeSet attr) throws badlocationexception {if (str = = null) return;if ((GetLength () + str.length ()) <= limit) {super.insertstring (offset, str, attr);//Call Parent class method}}}
The end~
TextField Limit Input Length