JSpinner
The JSpinner class enables the user to "spin" through a range of items using small up and down arrow buttons:
JSpinner spinner = new JSpinner(); panel.add(spinner);
- By default, the spinner allows the spinning through an unbounded range of integer values, defaulting to zero.
You can use the setValue() method to change the default value:
spinner.setValue(123);
The getValue() method retrieves the selected value as an Object, so if you are using the default integers you need to cast:
int v = (Integer) spinner.getValue();
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):
private class ColourSpinnerModel extends SpinnerListModel {
public ColourSpinnerModel() {
ArrayList<String> colours = new ArrayList<String>();
colours.add("Red");
colours.add("Green");
colours.add("Blue");
setList(colours);
}
}
- You will need to import
java.util.* - The
setList()method assigns the list of strings to the model
To use the model, you instantiate an object of its type and assign it to the JSpinner:
ColourSpinnerModel model = new ColourSpinnerModel(); JSpinner spinner = new JSpinner(model);
Another convenience class you can use is SpinnerNumberModel, which is useful if you need to restrict the range of numbers to spin through:
SpinnerNumberModel model = new SpinnerNumberModel(0, 0, 100, 10);
- The first argument value indicates the initial default value – here it is zero
- The second argument value indicates the minimum allowed value – here it is also zero
- The third argument value indicates the maximum allowed value – here it is one hundred
- The fourth argument value indicates the step-size, that is, the value by which the selected value is incremented or decremented whenever a spin button is clicked. Normally this will be one, but here it is ten
Comments