A single line input field that lets the user select a number or an object value from an ordered sequence. Spinners typically provide a pair of tiny arrow buttons for stepping through the elements of the sequence. The keyboard up/down arrow keys also cycle through the elements. The user may also be allowed to type a (legal) value directly into the spinner. Although combo boxes provide similar functionality, spinners are sometimes preferred because they don't require a drop down list that can obscure important data.
A JSpinner
's sequence value is defined by its SpinnerModel
. The model
can be specified as a constructor argument and changed with the model
property. SpinnerModel
classes for some common types are provided: SpinnerListModel
, SpinnerNumberModel
, and SpinnerDateModel
.
A JSpinner
has a single child component that's responsible for displaying and potentially changing the current element or value of the model, which is called the editor
. The editor is created by the JSpinner
's constructor and can be changed with the editor
property. The JSpinner
's editor stays in sync with the model by listening for ChangeEvent
s. If the user has changed the value displayed by the editor
it is possible for the model
's value to differ from that of the editor
. To make sure the model
has the same value as the editor use the commitEdit
method, eg:
try {
spinner.commitEdit();
}
catch (ParseException pe) {
// Edited value is invalid, spinner.getValue() will return
// the last valid value, you could revert the spinner to show that:
JComponent editor = spinner.getEditor();
if (editor instanceof DefaultEditor) {
((DefaultEditor)editor).getTextField().setValue(spinner.getValue());
}
// reset the value to some known value:
spinner.setValue(fallbackValue);
// or treat the last valid value as the current, in which
// case you don't need to do anything.
}
return spinner.getValue();
For information and examples of using spinner see How to Use Spinners , a section in The Java Tutorial.
Warning: Swing is not thread safe. For more information see Swing's Threading Policy .
Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans™ has been added to the java.beans
package. Please see XMLEncoder
.