Search code examples
javaswingjspinner

How to get JSpinner min and max values in order to set a random value


I have a function that will use JSpinner.setValue() to assign a random value within the spinner's bounds. Of course, I need to know the spinner's minimum and maximum values, which are already assigned. At this point, I'm cycling through the entire spinner to determine these values. Is there a better way to find them? Something like

JSpinner.getModel().getMaxValue();

I have already read through similar questions including this one: JSpinner get Max Min Value, but it didn't answer my question. Any help is appreciated.


Solution

  • I assume that you are talking about numerical values. In such case you should use NumberSpinnerModel - this class already has method you requested: getMaximum() and getMinimum().

    JSpinner.getModel() returns SpinnerModel so you will have to cast it to SpinnerNumberModel. This is ofcourse if you are really using this model with your spinner - cast will fail otherwise.