Make JSpinner completely numeric
You could try setAllowsInvalid(false)
as follows:
JFormattedTextField txt = ((JSpinner.NumberEditor) mySpinner.getEditor()).getTextField();
((NumberFormatter) txt.getFormatter()).setAllowsInvalid(false);
By setting this property, the Jspinner will show only valid values in the field and ignores all other values entered by the user. also the user will not be able to delete the whole value entered in the Jspinner i.e. if the user tries to select the entire value and delete it will not be allowed. User can edit the field only with a valid value other wise the it will seem like un-editable.
Balanivash
Hey, am a guy, whose heart lies in anything that has to do with computers. Kinda workaholic if it comes to working with comps, but for anything else don't depend on me to do anything unless you have asked me till you get tired and do it yourself..:) . Have tried my hands in design, building websites, applications, organizing workshops, events etc.. and still exploring anything that has to do with computers , and mainly FOSS and linux based. #SOreadytohelp
Updated on June 15, 2022Comments
-
Balanivash almost 2 years
I've a Jspinner that can vary from
minimum
tomaximum
at steps of0.1
. This is working perfectly fine. Now, I set the editor ofJSpinner
asNumberEditor
as the user can edit the textbox and I want only numeric values from this. This is also working, that is whatever the user may enter, the editor gives me only the numbers in the editor when I get the value usingmySpinner.getValue().toString();
. Now cones the problem. I want the textbox to accept only numeric values and.(decimal point)
, that is, if the user tries to enter anything apart from0-9
and.
, it should not echo it in the textbox.JSpinner mySpinner = new JSpinner(); mySpinner.setModel(new SpinnerNumberModel(default,minimum,maximum,0.1)); mySpinner.setEditor(new JSpinner.NumberEditor(mySpinner,"##.#"));
Can someone help me with this. Thanks :)
-
Balanivash almost 13 yearsSo, after doing this, should I do anything to link this with my
JSpinner
's testbox? -
Balanivash almost 13 yearsLike this doesnt allow me to input characters, but the problem is, this doesnt allow me to input
.
also, which I need, and I cant clear the field, requires at least one number in it all the time , is this a property of theJFormattedTextField
-
Dilini Rajapaksha almost 13 yearsyes you cant clear the field but you can set the correct format for the field as below:
NumberFormatter formatter = (NumberFormatter) txt.getFormatter(); DecimalFormat decimalFormat = new DecimalFormat("0.0"); formatter.setFormat(decimalFormat); formatter.setAllowsInvalid(false);
-
Dilini Rajapaksha almost 13 yearsThe above solution will allow to input
.
and to clear the field refer link -
iGhost about 5 yearsWork perfectly 👌