java - Using Document FIlter to filter multiple periods(.) -
lets user has input double value jtextfield gets calculated.
if user used more 1 period trigger numberformatexception, assume solution using document filter filter out periods or catching exception , notifying user of invalid input
currenty using documentfilter allow digits , periods, problem how filter out second period
plaindocument filter = new plaindocument(); filter.setdocumentfilter(new documentfilter() { @override public void insertstring(filterbypass fb, int off, string str, attributeset attr) throws badlocationexception { fb.insertstring(off, str.replaceall("[^0-9.]", ""), attr); } @override public void replace(filterbypass fb, int off, int len, string str, attributeset attr) throws badlocationexception { fb.replace(off, len, str.replaceall("[^0-9.]", ""), attr); } }); apm.setdocument(filter);
example
invalid input: 1.2.2
valid input: 1.22
my suggestion change overridden insertstring
, replace
methods checks whether "."
has been inserted earlier before insert or replace , change filter in way 'period' replaced blank string if subsequent time period
character inserted user. have illustrated below:
@override public void insertstring(filterbypass fb, int off, string str, attributeset attr) throws badlocationexception { string regexp; document doc = fb.getdocument(); if(doc.gettext(0, doc.getlength()).indexof(".") == -1){ regexp = "[^0-9.]"; } else { regexp = "[^0-9]"; } fb.insertstring(off, str.replaceall(regexp, ""), attr); } @override public void replace(filterbypass fb, int off, int len, string str, attributeset attr) throws badlocationexception { string regexp; document doc = fb.getdocument(); if(doc.gettext(0, doc.getlength()).indexof(".") == -1){ regexp = "[^0-9.]"; } else { regexp = "[^0-9]"; } fb.replace(off, len, str.replaceall(regexp, ""), attr); }
the above code allow 'period' inserted once in document
documentfilter
set.
Comments
Post a Comment