- java.lang.Object
-
- java.awt.Component
-
- java.awt.Container
-
- javax.swing.JComponent
-
- javax.swing.JSpinner
-
- All Implemented Interfaces:
- ImageObserver, MenuContainer, Serializable, Accessible
public class JSpinner extends JComponent implements Accessible
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 itsSpinnerModel. Themodelcan be specified as a constructor argument and changed with themodelproperty.SpinnerModelclasses for some common types are provided:SpinnerListModel,SpinnerNumberModel, andSpinnerDateModel.A
JSpinnerhas a single child component that's responsible for displaying and potentially changing the current element or value of the model, which is called theeditor. The editor is created by theJSpinner's constructor and can be changed with theeditorproperty. TheJSpinner's editor stays in sync with the model by listening forChangeEvents. If the user has changed the value displayed by theeditorit is possible for themodel's value to differ from that of theeditor. To make sure themodelhas the same value as the editor use thecommitEditmethod, 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 JavaBeansTM has been added to the
java.beanspackage. Please seeXMLEncoder.- Since:
- 1.4
- See Also:
SpinnerModel,AbstractSpinnerModel,SpinnerListModel,SpinnerNumberModel,SpinnerDateModel,JFormattedTextField
-
-
Nested Class Summary
Nested Classes Modifier and Type Class and Description protected classJSpinner.AccessibleJSpinnerAccessibleJSpinnerimplements accessibility support for theJSpinnerclass.static classJSpinner.DateEditorAn editor for aJSpinnerwhose model is aSpinnerDateModel.static classJSpinner.DefaultEditorA simple base class for more specialized editors that displays a read-only view of the model's current value with aJFormattedTextField.static classJSpinner.ListEditorAn editor for aJSpinnerwhose model is aSpinnerListModel.static classJSpinner.NumberEditorAn editor for aJSpinnerwhose model is aSpinnerNumberModel.-
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
-
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
-
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
-
-
Field Summary
-
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
-
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
-
-
Constructor Summary
Constructors Constructor and Description JSpinner()Constructs a spinner with anInteger SpinnerNumberModelwith initial value 0 and no minimum or maximum limits.JSpinner(SpinnerModel model)Constructs a spinner for the given model.
-
Method Summary
Methods Modifier and Type Method and Description voidaddChangeListener(ChangeListener listener)Adds a listener to the list that is notified each time a change to the model occurs.voidcommitEdit()Commits the currently edited value to theSpinnerModel.protected JComponentcreateEditor(SpinnerModel model)This method is called by the constructors to create theJComponentthat displays the current value of the sequence.protected voidfireStateChanged()Sends aChangeEvent, whose source is thisJSpinner, to eachChangeListener.AccessibleContextgetAccessibleContext()Gets theAccessibleContextfor theJSpinnerChangeListener[]getChangeListeners()Returns an array of all theChangeListeners added to this JSpinner with addChangeListener().JComponentgetEditor()Returns the component that displays and potentially changes the model's value.SpinnerModelgetModel()Returns theSpinnerModelthat defines this spinners sequence of values.ObjectgetNextValue()Returns the object in the sequence that comes after the object returned bygetValue().ObjectgetPreviousValue()Returns the object in the sequence that comes before the object returned bygetValue().SpinnerUIgetUI()Returns the look and feel (L&F) object that renders this component.StringgetUIClassID()Returns the suffix used to construct the name of the look and feel (L&F) class used to render this component.ObjectgetValue()Returns the current value of the model, typically this value is displayed by theeditor.voidremoveChangeListener(ChangeListener listener)Removes aChangeListenerfrom this spinner.voidsetEditor(JComponent editor)Changes theJComponentthat displays the current value of theSpinnerModel.voidsetModel(SpinnerModel model)Changes the model that represents the value of this spinner.voidsetUI(SpinnerUI ui)Sets the look and feel (L&F) object that renders this component.voidsetValue(Object value)Changes current value of the model, typically this value is displayed by theeditor.voidupdateUI()Resets the UI property with the value from the current look and feel.-
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
-
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTree
-
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
-
-
-
Constructor Detail
-
JSpinner
public JSpinner(SpinnerModel model)
Constructs a spinner for the given model. The spinner has a set of previous/next buttons, and an editor appropriate for the model.- Throws:
NullPointerException- if the model isnull
-
JSpinner
public JSpinner()
Constructs a spinner with anInteger SpinnerNumberModelwith initial value 0 and no minimum or maximum limits.
-
-
Method Detail
-
getUI
public SpinnerUI getUI()
Returns the look and feel (L&F) object that renders this component.- Returns:
- the
SpinnerUIobject that renders this component
-
setUI
public void setUI(SpinnerUI ui)
Sets the look and feel (L&F) object that renders this component.- Parameters:
ui- theSpinnerUIL&F object- See Also:
UIDefaults.getUI(javax.swing.JComponent)
-
getUIClassID
public String getUIClassID()
Returns the suffix used to construct the name of the look and feel (L&F) class used to render this component.- Overrides:
getUIClassIDin classJComponent- Returns:
- the string "SpinnerUI"
- See Also:
JComponent.getUIClassID(),UIDefaults.getUI(javax.swing.JComponent)
-
updateUI
public void updateUI()
Resets the UI property with the value from the current look and feel.- Overrides:
updateUIin classJComponent- See Also:
UIManager.getUI(javax.swing.JComponent)
-
createEditor
protected JComponent createEditor(SpinnerModel model)
This method is called by the constructors to create theJComponentthat displays the current value of the sequence. The editor may also allow the user to enter an element of the sequence directly. An editor must listen forChangeEventson themodeland keep the value it displays in sync with the value of the model.Subclasses may override this method to add support for new
SpinnerModelclasses. Alternatively one can just replace the editor created here with thesetEditormethod. The default mapping from model type to editor is:-
SpinnerNumberModel => JSpinner.NumberEditor -
SpinnerDateModel => JSpinner.DateEditor -
SpinnerListModel => JSpinner.ListEditor - all others =>
JSpinner.DefaultEditor
- Parameters:
model- the value of getModel- Returns:
- a component that displays the current value of the sequence
- See Also:
getModel(),setEditor(javax.swing.JComponent)
-
-
setModel
public void setModel(SpinnerModel model)
Changes the model that represents the value of this spinner. If the editor property has not been explicitly set, the editor property is (implicitly) set after the"model"PropertyChangeEventhas been fired. The editor property is set to the value returned bycreateEditor, as in:setEditor(createEditor(model));
- Parameters:
model- the newSpinnerModel- Throws:
IllegalArgumentException- if model isnull- See Also:
getModel(),getEditor(),setEditor(javax.swing.JComponent)
-
getModel
public SpinnerModel getModel()
Returns theSpinnerModelthat defines this spinners sequence of values.- Returns:
- the value of the model property
- See Also:
setModel(javax.swing.SpinnerModel)
-
getValue
public Object getValue()
Returns the current value of the model, typically this value is displayed by theeditor. If the user has changed the value displayed by theeditorit is possible for themodel's value to differ from that of theeditor, refer to the class level javadoc for examples of how to deal with this.This method simply delegates to the
model. It is equivalent to:getModel().getValue()
-
setValue
public void setValue(Object value)
Changes current value of the model, typically this value is displayed by theeditor. If theSpinnerModelimplementation doesn't support the specified value then anIllegalArgumentExceptionis thrown.This method simply delegates to the
model. It is equivalent to:getModel().setValue(value)
- Throws:
IllegalArgumentException- ifvalueisn't allowed- See Also:
getValue(),SpinnerModel.setValue(java.lang.Object)
-
getNextValue
public Object getNextValue()
Returns the object in the sequence that comes after the object returned bygetValue(). If the end of the sequence has been reached then returnnull. Calling this method does not effectvalue.This method simply delegates to the
model. It is equivalent to:getModel().getNextValue()
- Returns:
- the next legal value or
nullif one doesn't exist - See Also:
getValue(),getPreviousValue(),SpinnerModel.getNextValue()
-
addChangeListener
public void addChangeListener(ChangeListener listener)
Adds a listener to the list that is notified each time a change to the model occurs. The source ofChangeEventsdelivered toChangeListenerswill be thisJSpinner. Note also that replacing the model will not affect listeners added directly to JSpinner. Applications can add listeners to the model directly. In that case is that the source of the event would be theSpinnerModel.- Parameters:
listener- theChangeListenerto add- See Also:
removeChangeListener(javax.swing.event.ChangeListener),getModel()
-
removeChangeListener
public void removeChangeListener(ChangeListener listener)
Removes aChangeListenerfrom this spinner.- Parameters:
listener- theChangeListenerto remove- See Also:
fireStateChanged(),addChangeListener(javax.swing.event.ChangeListener)
-
getChangeListeners
public ChangeListener[] getChangeListeners()
Returns an array of all theChangeListeners added to this JSpinner with addChangeListener().- Returns:
- all of the
ChangeListeners added or an empty array if no listeners have been added - Since:
- 1.4
-
fireStateChanged
protected void fireStateChanged()
Sends aChangeEvent, whose source is thisJSpinner, to eachChangeListener. When aChangeListenerhas been added to the spinner, this method method is called each time aChangeEventis received from the model.
-
getPreviousValue
public Object getPreviousValue()
Returns the object in the sequence that comes before the object returned bygetValue(). If the end of the sequence has been reached then returnnull. Calling this method does not effectvalue.This method simply delegates to the
model. It is equivalent to:getModel().getPreviousValue()
- Returns:
- the previous legal value or
nullif one doesn't exist - See Also:
getValue(),getNextValue(),SpinnerModel.getPreviousValue()
-
setEditor
public void setEditor(JComponent editor)
Changes theJComponentthat displays the current value of theSpinnerModel. It is the responsibility of this method to disconnect the old editor from the model and to connect the new editor. This may mean removing the old editorsChangeListenerfrom the model or the spinner itself and adding one for the new editor.- Parameters:
editor- the new editor- Throws:
IllegalArgumentException- if editor isnull- See Also:
getEditor(),createEditor(javax.swing.SpinnerModel),getModel()
-
getEditor
public JComponent getEditor()
Returns the component that displays and potentially changes the model's value.- Returns:
- the component that displays and potentially changes the model's value
- See Also:
setEditor(javax.swing.JComponent),createEditor(javax.swing.SpinnerModel)
-
commitEdit
public void commitEdit() throws ParseExceptionCommits the currently edited value to theSpinnerModel.If the editor is an instance of
DefaultEditor, the call if forwarded to the editor, otherwise this does nothing.- Throws:
ParseException- if the currently edited value couldn't be commited.
-
getAccessibleContext
public AccessibleContext getAccessibleContext()
Gets theAccessibleContextfor theJSpinner- Specified by:
getAccessibleContextin interfaceAccessible- Overrides:
getAccessibleContextin classJComponent- Returns:
- the
AccessibleContextfor theJSpinner - Since:
- 1.5
-
-
Deutsche Übersetzung
Sie haben gebeten, diese Seite auf Deutsch zu besuchen. Momentan ist nur die Oberfläche übersetzt, aber noch nicht der gesamte Inhalt.Wenn Sie mir bei Übersetzungen helfen wollen, ist Ihr Beitrag willkommen. Alles, was Sie tun müssen, ist, sich auf der Website zu registrieren und mir eine Nachricht zu schicken, in der Sie gebeten werden, Sie der Gruppe der Übersetzer hinzuzufügen, die Ihnen die Möglichkeit gibt, die gewünschten Seiten zu übersetzen. Ein Link am Ende jeder übersetzten Seite zeigt an, dass Sie der Übersetzer sind und einen Link zu Ihrem Profil haben.
Vielen Dank im Voraus.
Dokument erstellt 11/06/2005, zuletzt geändert 04/03/2020
Quelle des gedruckten Dokuments:https://www.gaudry.be/de/java-api-rf-javax/swing/JSpinner.html
Die Infobro ist eine persönliche Seite, deren Inhalt in meiner alleinigen Verantwortung liegt. Der Text ist unter der CreativeCommons-Lizenz (BY-NC-SA) verfügbar. Weitere Informationen auf die Nutzungsbedingungen und dem Autor.
Referenzen
Diese Verweise und Links verweisen auf Dokumente, die während des Schreibens dieser Seite konsultiert wurden, oder die zusätzliche Informationen liefern können, aber die Autoren dieser Quellen können nicht für den Inhalt dieser Seite verantwortlich gemacht werden.
Der Autor dieser Website ist allein dafür verantwortlich, wie die verschiedenen Konzepte und Freiheiten, die mit den Nachschlagewerken gemacht werden, hier dargestellt werden. Denken Sie daran, dass Sie mehrere Quellinformationen austauschen müssen, um das Risiko von Fehlern zu reduzieren.