By Tony Bevis on Thursday, 19 October 2023
Category: Java

Java programming course: 14.10 JSpinner

JSpinner

The JSpinner class enables the user to "spin" through a range of items using small up and down arrow buttons:

You can use the setValue() method to change the default value:

The getValue() method retrieves the selected value as an Object, so if you are using the default integers you need to cast:

The above statement shows an example of autoboxing, in that Java will convert between the object type Integer and the primitive type int. Without autoboxing you would have had to use a two-step process:

Integer temp = (Integer) spinner.getValue();

int v = temp.intValue();

If you are wondering why getValue() returns Object rather than an int it is because you can spin any type of object, such as strings or even images. To do this you need to make use of a SpinnerModel to supply the range of spinnable objects to the spinner.

Here is an example inner class called ColourSpinnerModel which extends the Java supplied SpinnerListModel (and which implements SpinnerModel):


To use the model, you instantiate an object of its type and assign it to the JSpinner:

Another convenience class you can use is SpinnerNumberModel, which is useful if you need to restrict the range of numbers to spin through:

Next lesson: 14.11 JList

Related Posts

Leave Comments