APIdia Launch Partner
Top Description Inners Fields Constructors Methods
javax.swing

public Class JSpinner

extends JComponent
implements Accessible
Class Inheritance
All Implemented Interfaces
javax.accessibility.Accessible
Annotations
@JavaBean
defaultProperty:UI
description:A single line input field that lets the user select a number or an object value from an ordered set.
@SwingContainer:false
@SuppressWarnings:serial
Imports
java.awt.Component, .ComponentOrientation, .Container, .Dimension, .Font, .Insets, .LayoutManager, .Point, .Rectangle, java.awt.event.ActionEvent, java.beans.BeanProperty, .JavaBean, .PropertyChangeEvent, .PropertyChangeListener, java.io.IOException, .ObjectOutputStream, .Serial, .Serializable, java.text.DateFormat, .DecimalFormat, .NumberFormat, .ParseException, .SimpleDateFormat, java.text.spi.DateFormatProvider, .NumberFormatProvider, java.util.Date, .Locale, javax.accessibility.Accessible, .AccessibleAction, .AccessibleContext, .AccessibleEditableText, .AccessibleRole, .AccessibleText, .AccessibleValue, javax.swing.event.ChangeEvent, .ChangeListener, .EventListenerList, javax.swing.plaf.FontUIResource, .SpinnerUI, .UIResource, javax.swing.text.AttributeSet, .BadLocationException, .DateFormatter, .DefaultFormatterFactory, .DocumentFilter, .NumberFormatter, sun.util.locale.provider.LocaleProviderAdapter, .LocaleResources

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 ChangeEvents. 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 java.beans.XMLEncoder.

Authors
Hans Muller, Lynn Monsanto (accessibility)
Since
1.4
See Also
SpinnerModel, AbstractSpinnerModel, SpinnerListModel, SpinnerNumberModel, SpinnerDateModel, JFormattedTextField

Nested and Inner Type Summary

Modifier and TypeClass and Description
protected class
JSpinner.AccessibleJSpinner

AccessibleJSpinner implements accessibility support for the JSpinner class.

public static class
JSpinner.DateEditor

An editor for a JSpinner whose model is a SpinnerDateModel.

private static class
JSpinner.DateEditorFormatter

This subclass of javax.swing.DateFormatter maps the minimum/maximum properties to the start/end properties of a SpinnerDateModel.

public static class
JSpinner.DefaultEditor

A simple base class for more specialized editors that displays a read-only view of the model's current value with a JFormattedTextField.

private static class
JSpinner.DisabledAction

An Action implementation that is always disabled.

public static class
JSpinner.ListEditor

An editor for a JSpinner whose model is a SpinnerListModel.

private class
JSpinner.ModelListener

We pass Change events along to the listeners with the the slider (instead of the model itself) as the event source.

public static class
JSpinner.NumberEditor

An editor for a JSpinner whose model is a SpinnerNumberModel.

private static class
JSpinner.NumberEditorFormatter

This subclass of javax.swing.NumberFormatter maps the minimum/maximum properties to a SpinnerNumberModel and initializes the valueClass of the NumberFormatter to match the type of the initial models value.

Field Summary

Modifier and TypeField and Description
private transient ChangeEvent
private static final Action
private JComponent
private boolean
private SpinnerModel
private ChangeListener
private static final String
Inherited from javax.swing.JComponent:
DEBUG_GRAPHICS_LOADEDfocusControllerivSourceComponentlistenerListpaintingChildTOOL_TIP_TEXT_KEYuiUNDEFINED_CONDITIONWHEN_ANCESTOR_OF_FOCUSED_COMPONENTWHEN_FOCUSEDWHEN_IN_FOCUSED_WINDOW

Constructor Summary

AccessConstructor and Description
public
JSpinner(SpinnerModel
a model for the new spinner
model
)

Constructs a spinner for the given model.

public
JSpinner()

Constructs a spinner with an Integer SpinnerNumberModel with initial value 0 and no minimum or maximum limits.

Method Summary

Modifier and TypeMethod and Description
public void
addChangeListener(ChangeListener
the ChangeListener to add
listener
)

Adds a listener to the list that is notified each time a change to the model occurs.

public void
commitEdit()

Commits the currently edited value to the SpinnerModel.

protected JComponent

Returns:

a component that displays the current value of the sequence
createEditor
(SpinnerModel
the value of getModel
model
)

This method is called by the constructors to create the JComponent that displays the current value of the sequence.

protected void
fireStateChanged()

Sends a ChangeEvent, whose source is this JSpinner, to each ChangeListener.

public AccessibleContext

Returns:

the AccessibleContext for the JSpinner
getAccessibleContext
()

Overrides java.awt.Component.getAccessibleContext.

Implements javax.accessibility.Accessible.getAccessibleContext.

Gets the AccessibleContext for the JSpinner

public ChangeListener[]

Returns:

all of the ChangeListeners added or an empty array if no listeners have been added
getChangeListeners
()

Returns an array of all the ChangeListeners added to this JSpinner with addChangeListener().

public JComponent

Returns:

the component that displays and potentially changes the model's value
getEditor
()

Returns the component that displays and potentially changes the model's value.

public SpinnerModel

Returns:

the value of the model property
getModel
()

Returns the SpinnerModel that defines this spinners sequence of values.

public Object

Returns:

the next legal value or null if one doesn't exist
getNextValue
()

Returns the object in the sequence that comes after the object returned by getValue().

public Object

Returns:

the previous legal value or null if one doesn't exist
getPreviousValue
()

Returns the object in the sequence that comes before the object returned by getValue().

public SpinnerUI

Returns:

the SpinnerUI object that renders this component
getUI
()

Overrides javax.swing.JComponent.getUI.

Returns the look and feel (L&F) object that renders this component.

public String

Returns:

the string "SpinnerUI"
getUIClassID
()

Overrides javax.swing.JComponent.getUIClassID.

Returns the suffix used to construct the name of the look and feel (L&F) class used to render this component.

public Object

Returns:

the current value of the model
getValue
()

Returns the current value of the model, typically this value is displayed by the editor.

public void
removeChangeListener(ChangeListener
the ChangeListener to remove
listener
)

Removes a ChangeListener from this spinner.

public void
setEditor(JComponent
the new editor
editor
)

Changes the JComponent that displays the current value of the SpinnerModel.

public void
setModel(SpinnerModel
the new SpinnerModel
model
)

Changes the model that represents the value of this spinner.

public void
setUI(SpinnerUI
the SpinnerUI L&F object
ui
)

Sets the look and feel (L&F) object that renders this component.

public void
setValue(Object
new value for the spinner
value
)

Changes current value of the model, typically this value is displayed by the editor.

public void
updateUI()

Overrides javax.swing.JComponent.updateUI.

Resets the UI property with the value from the current look and feel.

private void
writeObject(ObjectOutputStream s)

Hides javax.swing.JComponent.writeObject.

Before writing a JComponent to an ObjectOutputStream we temporarily uninstall its UI.

Inherited from javax.swing.JComponent:
_paintImmediatelyaddAncestorListeneraddNotifyaddVetoableChangeListeneralwaysOnTopcheckIfChildObscuredBySiblingclientPropertyChangedcomponentInputMapChangedcomputeVisibleRectcomputeVisibleRectcompWriteObjectNotifycontainscreateToolTipdisabledndDonedropLocationForPointenablefirePropertyChangefirePropertyChangefirePropertyChangefireVetoableChangegetActionForKeyStrokegetActionMapgetActionMapgetAlignmentXgetAlignmentYgetAncestorListenersgetAutoscrollsgetBaselinegetBaselineResizeBehaviorgetBordergetBoundsgetClientPropertygetComponentGraphicsgetComponentPopupMenugetConditionForKeyStrokegetCreatedDoubleBuffergetDebugGraphicsOptionsgetDefaultLocalegetFontMetricsgetGraphicsgetGraphicsInvokedgetHeightgetInheritsPopupMenugetInputMapgetInputMapgetInputMapgetInputVerifiergetInsetsgetInsetsgetListenersgetLocationgetManagingFocusBackwardTraversalKeysgetManagingFocusForwardTraversalKeysgetMaximumSizegetMinimumSizegetNextFocusableComponentgetPopupLocationgetPreferredSizegetRegisteredKeyStrokesgetRootPanegetSizegetToolTipLocationgetToolTipTextgetToolTipTextgetTopLevelAncestorgetTransferHandlergetVerifyInputWhenFocusTargetgetVetoableChangeListenersgetVisibleRectgetWidthgetWriteObjCountergetXgetYgrabFocushideisDoubleBufferedisLightweightComponentisManagingFocusisOpaqueisOptimizedDrawingEnabledisPaintingisPaintingForPrintisPaintingOriginisPaintingTileisRequestFocusEnabledisValidateRootpaintpaintBorderpaintChildrenpaintComponentpaintForceDoubleBufferedpaintImmediatelypaintImmediatelypaintToOffscreenparamStringprintprintAllprintBorderprintChildrenprintComponentprocessComponentKeyEventprocessKeyBindingprocessKeyBindingsprocessKeyBindingsForAllComponentsprocessKeyEventprocessMouseEventprocessMouseMotionEventputClientPropertyrectangleIsObscuredregisterKeyboardActionregisterKeyboardActionremoveAncestorListenerremoveNotifyremoveVetoableChangeListenerrepaintrepaintrequestDefaultFocusrequestFocusrequestFocusrequestFocusInWindowrequestFocusInWindowresetKeyboardActionsreshaperevalidatesafelyGetGraphicssafelyGetGraphicsscrollRectToVisiblesetActionMapsetAlignmentXsetAlignmentYsetAutoscrollssetBackgroundsetBordersetComponentPopupMenusetCreatedDoubleBuffersetDebugGraphicsOptionssetDefaultLocalesetDoubleBufferedsetDropLocationsetEnabledsetFocusTraversalKeyssetFontsetForegroundsetInheritsPopupMenusetInputMapsetInputVerifiersetMaximumSizesetMinimumSizesetNextFocusableComponentsetOpaquesetPaintingChildsetPreferredSizesetRequestFocusEnabledsetToolTipTextsetTransferHandlersetUIsetUIPropertysetVerifyInputWhenFocusTargetsetVisiblesetWriteObjCountershouldDebugGraphicssuperProcessMouseMotionEventunregisterKeyboardActionupdate