java - Block text-writing after n characters -
i have code, "disables" user input on jtextfield after n characters inserted:
jtextfield tf = new jtextfield(); tf.addkeylistener(new keyadapter() { public void keytyped(keyevent e) { if (((jtextfield) e.getsource()).gettext().length() > n) { e.consume(); } } });
it works, wondering if there alternative, because tried on old slow computer , when type in textfield letter added, disappear... avoid using e.consume()
after user input , directly prevent insertion instead.
is possible?
edit
i forgot mention used jtextfield
example, code work generic text input components jtextpane
, jtextarea
, etc
you can use documentsizefilter
class
which made specific use: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/textcomponentdemoproject/src/components/documentsizefilter.java
tutorial on how within implementing document filter section:
quoting there:
to limit characters allowed in document, documentsizefilter overrides documentfilter class's insertstring method, called each time text inserted document. overrides replace method, called when user pastes in new text. in general, text insertion can result when user types or pastes in new text, or when settext method called. here documentsizefilter class's implementation of insertstring method:
public void insertstring(filterbypass fb, int offs, string str, attributeset a) throws badlocationexception { if ((fb.getdocument().getlength() + str.length()) <= maxcharacters) super.insertstring(fb, offs, str, a); else toolkit.getdefaulttoolkit().beep(); }
Comments
Post a Comment