Character input limit in TextField

xiaoxiao2021-03-06  56

1) java.awt.textfield version, I really can't think of other ways, this approach is relatively bad:

Public void setInputLimited (int min, int max textfield text) {

T.AddKeylistener (new java.awt.event.keyadapter () {public void keypressed (keyevent e) {if (E.GetKeyCode ()> max || E.GetKeyCode ()

T.SETTEXT (T. Gettext (). Substring (0, T. Gettext (). Length () -1));

}

}

});

}

2) javax.swing.jtextfield

JtextField and TextField are different. He has a setDocument (Document Doc) method that can set your input.

Such as

Import java.awt. *; import javax.swing.text. *;

Public void setInputLimited (int min, int max, jtextfield text) {

Text.SetDocument (new numberonlydocument ());

}

public class NumberOnlyDocument extends PlainDocument {private boolean haveDot = false; private int length = 0; private double max = Double.MIN_VALUE, min = Double.MAX_VALUE; public NumberOnlyDocument (double max, double min) {if (max> = min) { this.max = max; this.min = min;}} public void insertString (int offs, String str, AttributeSet a) throws BadLocationException {if (str == null) {return;} char [] number = str.toCharArray ( ); For (int i = 0; i = '0' && number [i] <= '9' | | Number [i] == '.' || Number [i] == '-' || Number [i] == ' ')) {= == length - 1) {Remove (OFFS I 1);} else {return;}

转载请注明原文地址:https://www.9cbs.com/read-115108.html

New Post(0)