java - Multiple Jtextfields to be filled before Jbutton enable -
hi badly need search jtextfield filled before jbutton enables, documentlistener people use determined if jtextfield being populated. tried documentlistener , works want jtextfield must not empty before jbutton enables here code.
ftext.getdocument().adddocumentlistener(new documentlistener() { @override public void insertupdate(documentevent e) { change(); } @override public void removeupdate(documentevent e) { change(); } @override public void changedupdate(documentevent e) { change(); } private void change(){ if (ftext.gettext().equals("") && mtext.gettext().equals("") && ltext.gettext().equals("") && addtext.gettext().equals("")) { savebutton.setenabled(false); } else { savebutton.setenabled(true); } } });
if (ftext.gettext().equals("") && mtext.gettext().equals("") && ltext.gettext().equals("") && addtext.gettext().equals(""))
means fields must empty. times need read logic aloud...
"if field empty , field empty , field empty..."
if used ||
(or) instead, mean if 1 of fields empty statement true
example...
if (ftext.gettext().equals("") || mtext.gettext().equals("") || ltext.gettext().equals("") || addtext.gettext().equals("")) {...
you should consider using .gettext().isempty()
or .gettext().trim().isempty()
if fields shouldn't contain spaces.
you might consider writing single documentlistener
implementation instead of creating new anonymous class each field
public class fieldvalidationhandler implements documentlistener() { private list<jtextfield> monitorfields; public fieldvalidationhandler(jtextfield... fields) { monitorfields = arrays.aslist(fields); (jtextfield field : monitorfields) { field.getdocument().adddocumentlistener(this); } } @override public void insertupdate(documentevent e) { change(); } @override public void removeupdate(documentevent e) { change(); } @override public void changedupdate(documentevent e) { change(); } private void change(){ boolean enabled = true; (jtextfield field : monitorfields) { if (field.gettext().trim().isempty()) { enabled = false; break; } } savebutton.setenabled(enabled); } }
then you'd create single instance...
fieldvalidationhandler handler = new fieldvalidationhandler(ftext, mtext, ltext, addtext);
now, approach little sneaky, in adds documentlistener
fields specify via constructor automatically.
another approach might have kind "validation" controller, pass handler , call kind of "validate" method when change
called.
this separate listener fields, matter of context @ time.
i have "register" , "unregister" process allow add or remove fields need to
Comments
Post a Comment