问题
I have a jSpinner with a SpinnerNumberModel like this:
spinnerModelFix = new SpinnerNumberModel(0, 0, 65535, 1);
JSpinner fixedValueSpinner = new JSpinner(spinnerModelFix);
I just want to show Integers in the spinner, so that if the user insert letters they aren't shown.
I thought I should extends SpinnerNumberModel and override the fireStateChanged() method...
But I'm not sure what I need to do in that method.
Can anyone give me some hint?
回答1:
yes is possible and workaround is quite simple,
there are two ways how to do it, have to derive
JTextFieldorJFormattedTextFieldfromJSpinner,then to add
a)
DocumentListenerb)
DocumentFilter
I think that usage of DocumentFilter is easiest for code workaround, better, maybe safer
回答2:
You can try setAllowsInvalid(false) on spinner's formatter. For example:
SpinnerNumberModel spinnerModelFix = new SpinnerNumberModel(0, 0, 65535, 1);
JSpinner fixedValueSpinner = new JSpinner(spinnerModelFix);
JFormattedTextField textField = ((JSpinner.NumberEditor) fixedValueSpinner
.getEditor()).getTextField();
((NumberFormatter) textField.getFormatter()).setAllowsInvalid(false);
来源:https://stackoverflow.com/questions/12825622/avoiding-jspinner-to-take-letters