1

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?

amp
  • 11,754
  • 18
  • 77
  • 133

2 Answers2

3
  • yes is possible and workaround is quite simple,

  • there are two ways how to do it, have to derive JTextField or JFormattedTextField from JSpinner,

  • then to add

    a) DocumentListener

    b) DocumentFilter

I think that usage of DocumentFilter is easiest for code workaround, better, maybe safer

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • @Max author of this idea is King of JTextComponents – mKorbel Oct 10 '12 at 19:11
  • This works, but when the displayed value is higher than 1000, arrows to increase or decrease the value doesn't work anymore... You know what could be the problem? – amp Oct 10 '12 at 21:21
  • aaach in the SpinnerNimberModel:-), there are four values, and two of them are min a max value :-) – mKorbel Oct 10 '12 at 22:17
  • I changed to `new SpinnerNumberModel(0, 0, 65535, 1)` but it don't solve the problem... – amp Oct 10 '12 at 23:59
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);
tenorsax
  • 21,123
  • 9
  • 60
  • 107
  • This seems to work more or less, but it don't let me deleted all the numbers if I want. It needs to have at least one digit... – amp Oct 10 '12 at 21:10
  • @amp `DocumentFilter` suggested by @mKorbel may be more suitable for your case. – tenorsax Oct 10 '12 at 21:30