Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 11

http://docs.oracle.com/javase/tutorial/uiswing/components/spinner.

html

How to Use Spinners


Spinners are similar to combo boxes and lists in that they let the user choose from a range of values. Like editable combo boxes, spinners allow the user to type in a value. Unlike combo boxes, spinners do not have a drop-down list that can cover up other components. Because spinners do not display possible values only the current value is visible they are often used instead of combo boxes or lists when the set of possible values is extremely large. !owever, spinners should only be used when the possible values and their se"uence are obvious. # spinner is a compound component with three subcomponents$ two small buttons and an editor. %he editor can be any &'omponent, but by default it is implemented as a panel that contains a formatted text field. %he spinner(s possible and current values are managed by its model. !ere is a picture of an application named SpinnerDemo that has three spinners used to specify dates$

%he code for the main class can be found in SpinnerDemo.java. %he )onth spinner displays the name of the first month in the user(s locale. %he possible values for this spinner are specified using an array of strings. %he *ear spinner displays one value of a range of integers, initiali+ed to the current year. %he #nother ,ate spinner displays one value in a range of Date ob-ects .initially the current date/ in a custom format that shows -ust a month and year. Try this: 1. 'lick the Launch button to run Spinner,emo using &ava0 1eb Start .download &,2 3 or later/. #lternatively, to compile and run the example yourself, consult the example index. 4. 1ith the )onth spinner, use the arrow buttons or keys to cycle forward and backward through the possible values. 5ote that the lowest value is the first month of the year .for example,

&anuary/ and the highest is the last .for example, ,ecember/. %he exact values depend on your locale. #lso note that the values do not cycle you cannot use the up arrow button or key to go from ,ecember directly to &anuary because the standard spinner models do not support cycling. 6. %ype in a valid month name for your locale for example, &uly. 5ote that the spinner automatically completes the month name. 7. )oving on to the *ear spinner, try typing a year over 899 years ago for example, 8:99 and then click on another spinner or press the %ab key to move the focus out of the spinner. Because this program restricts the spinner(s model to numbers within 899 years of the current year, 8:99 is invalid. 1hen the focus moves out of the spinner, the displayed text changes back to the last valid value. ;. )oving to the #nother ,ate spinner, use the arrow buttons or keys to change the date. 5ote that by default the first part of the date in this case, the month number changes. *ou can change which part of the date changes either by clicking the mouse or using the arrow keys to move to another part of the date.

To create a spinner, first create its model and then pass the model into the JSpinner constructor. For example:
String[] monthStrings = getMonthStrings(); //get month names SpinnerListModel monthModel = new SpinnerListModel(monthStrings); JSpinner spinner = new JSpinner(monthModel);

The rest of this section covers the following topics:


sing Standard Spinner !odels and "ditors Specif#ing Spinner Formatting $reating $ustom Spinner !odels and "ditors %etecting Spinner &alue $hanges The Spinner '() "xamples That se Spinners

Using Standard Spinner Models and Editors


The Swing '() provides three spinner models: Spinner*ist!odel The SpinnerListModel is a model whose values are defined +# an arra# of o+jects or a List o+ject. The !onth spinner in the SpinnerDemo example uses this model, initiali,ed with an arra# derived from the value returned +#

the getMonths method of the java.te t.Date!ormatS"m#ols class. See SpinnerDemo.java for details. Spinner-um+er!odel The Spinner$%m#erModel supports se.uences of num+ers which can +e expressed as do%#le o+jects, int o+jects, or $%m#er o+jects. /ou can specif# the minimum and maximum allowa+le values, as well as the step size 0 the amount of each increment or decrement. The /ear spinner uses this model, created with the following code:
SpinnerModel model = new Spinner$%m#erModel(&%rrent'ear( //initial val%e &%rrent'ear ) *++( //min &%rrent'ear , *++( //ma *); //step

Spinner%ate!odel The SpinnerDateModel supports se.uences of Date o+jects. /ou can specif# the minimum and maximum dates, as well as the field 1such as -alendar.'./02 to increment or decrement. -ote, however, that some t#pes of loo3 and feel ignore the specified field, and instead change the field that appears selected. The 'nother %ate spinner uses this model, created with the following code:
Date initDate = &alendar.get1ime(); &alendar.add(-alendar.'./0( )*++); Date earliestDate = &alendar.get1ime(); &alendar.add(-alendar.'./0( 2++); Date latestDate = &alendar.get1ime(); model = new SpinnerDateModel(initDate( earliestDate( latestDate( -alendar.'./0);

4hen #ou set the spinner5s model, the spinner5s editor is automaticall# set. The Swing '() provides an editor class corresponding to each of the three model classes listed a+ove. These classes 0 JSpinner.*ist"ditor, JSpinner.-um+er"ditor, and JSpinner.%ate"ditor 0 are all su+classes of the JSpinner.%efault"ditor class that feature edita+le formatted text fields. )f #ou use a model that does not have an editor associated with it, the editor is +# default a JSpinner.De3a%lt.ditor instance with a non6edita+le formatted text field.

Specifying Spinner Formatting


To change the formatting used in a standard spinner editor, #ou can create and set the editor #ourself. The JSpinner.$%m#er.ditor and JSpinner.Date.ditor classes have constructors that allow #ou to create an editor that formats its data in a particular wa#. For example, the following code sets up the 'nother %ate spinner so that instead of using the default date format, which is long and includes the time, it shows just a month and #ear in a compact wa#.
spinner.set.ditor(new JSpinner.Date.ditor(spinner( 4MM/""""4));

Note: /ou can pla# with date formats +# running -om#o5o Demo2 example. $lic3 the *aunch +utton to run $om+o7ox%emo8 using Java9 4e+ Start 1download J%: ; or later2. 'lternativel#, to compile and run the example #ourself, consult the example index.

For information a+out format strings, see the Formatting lesson of the )nternationali,ation trail.

To change the formatting when using a default editor, #ou can o+tain the editor5s formatted text field and invo3e methods on it. /ou can call those methods using the get1e t!ield method defined in the JSpinner.De3a%lt.ditor class. -ote that the Swing6provided editors are not formatted text fields. )nstead, the# are the J6anel instances that contain a formatted text field. <ere is an example of getting and invo3ing methods on the editor5s formatted text field:
//1wea7 the spinner8s 3ormatted te t 3ield. 3t3 = get1e t!ield(spinner); i3 (3t3 9= n%ll ) : 3t3.set-ol%mns(;); //spe&i3" more width than we need 3t3.set<ori=ontal/lignment(J1e t!ield.0>?<1); @ ... p%#li& J!ormatted1e t!ield get1e t!ield(JSpinner spinner) : J-omponent editor = spinner.get.ditor(); i3 (editor instan&eo3 JSpinner.De3a%lt.ditor) : ret%rn ((JSpinner.De3a%lt.ditor)editor).get1e t!ield(); @ else : S"stem.err.println(4Ane pe&ted editor t"peB 4 , spinner.get.ditor().get-lass() , 4 isn8t a des&endant o3 De3a%lt.ditor4); ret%rn n%ll; @ @

Creating Custom Spinner Models and Editors


)f the existing spinner models or editors do not meet #our needs, #ou can create #our own. The easiest route to creating a custom spinner model is to create a su+class of an existing /#stra&tSpinnerModel su+class that alread# does most of what #ou need. 'n alternative is to implement #our own class +# extending /#stra&tSpinnerModel class, which implements the event notifications re.uired for all spinner models.

The following su+class of SpinnerListModel implements a spinner model that c#cles through an arra# of o+jects. )t also lets #ou specif# a second spinner model that will +e updated whenever the c#cle +egins again. For example, if the arra# of o+jects is a list of months, the lin3ed model could +e for a spinner that displa#s the #ear. 4hen the month flips over from %ecem+er to Januar# the #ear is incremented. Similarl#, when the month flips +ac3 from Januar# to %ecem+er the #ear is decremented.
p%#li& &lass -"&lingSpinnerListModel e tends SpinnerListModel : C#je&t 3irstDal%e( lastDal%e; SpinnerModel lin7edModel = n%ll; p%#li& -"&lingSpinnerListModel(C#je&t[] val%es) : s%per(val%es); 3irstDal%e = val%es[+]; lastDal%e = val%es[val%es.length ) *]; @ p%#li& void setLin7edModel(SpinnerModel lin7edModel) : this.lin7edModel = lin7edModel; @ p%#li& C#je&t get$e tDal%e() : C#je&t val%e = s%per.get$e tDal%e(); i3 (val%e == n%ll) : val%e = 3irstDal%e; i3 (lin7edModel 9= n%ll) : lin7edModel.setDal%e(lin7edModel.get$e tDal%e()); @ @ ret%rn val%e; @ p%#li& C#je&t get6revio%sDal%e() : C#je&t val%e = s%per.get6revio%sDal%e(); i3 (val%e == n%ll) : val%e = lastDal%e; i3 (lin7edModel 9= n%ll) : lin7edModel.setDal%e(lin7edModel.get6revio%sDal%e()); @ @ ret%rn val%e; @ @

The -"&lingSpinnerListModel model is used for the !onth spinner in the SpinnerDemo2 example, an example that is almost identical to the SpinnerDemo. $lic3 the *aunch +utton to run Spinner%emo8 using Java9 4e+ Start 1download J%: ; or later2. 'lternativel#, to compile and run the example #ourself, consult the example index.

's we mentioned +efore, if #ou implement a spinner model that does not descend from SpinnerListModel, Spinner$%m#erModel, or SpinnerDateModel, then the spinner5s default editor is a non6edita+le instance of JSpinner.De3a%lt.ditor. 's #ou have alread# seen, #ou can set a spinner5s editor +# invo3ing the set.ditor method on the spinner after the spinner5s model propert# has +een set. 'n alternative to using set.ditor is to create a su+class of the JSpinner class and override its &reate.ditor method so that it returns a particular 3ind of editor whenever the spinner model is of a certain t#pe. )n theor# at least, #ou can use an# J-omponent instance as an editor. (ossi+ilities include using a su+class of a standard component such as JLa#el, or a component #ou have implemented from scratch, or a su+class of JSpinner.De3a%lt.ditor. The onl# re.uirements are that the editor must +e updated to reflect changes in the spinner5s value, and it must have a reasona+le preferred si,e. The editor should generall# also set its tool tip text to whatever tool tip text has +een specified for the spinner. 'n example of implementing an editor is provided in the next section.

Detecting Spinner Value Changes


/ou can detect that a spinner5s value has changed +# registering a change listener on either the spinner or its model. <ere is an example of implementing such a change listener. This example is from SpinnerDemoE, which is +ased on SpinnerDemo and uses a change listener to change the color of some text to match the value of the 'nother %ate spinner. $lic3 the *aunch +utton to run Spinner%emo= using Java9 4e+ Start 1download J%: ; or later2. 'lternativel#, to compile and run the example #ourself, consult the example index.

p%#li& &lass SpinnerDemoE e tends J6anel implements -hangeListener : prote&ted -alendar &alendar; prote&ted JSpinner dateSpinner; ... p%#li& SpinnerDemoE() : ... SpinnerDateModel dateModel = ...; ... setSeasonal-olor(dateModel.getDate()); //initiali=e &olor //Listen 3or &hanges on the date spinner. dateSpinner.add-hangeListener(this); ... @ p%#li& void state-hanged(-hange.vent e) : SpinnerModel dateModel = dateSpinner.getModel(); i3 (dateModel instan&eo3 SpinnerDateModel) : setSeasonal-olor(((SpinnerDateModel)dateModel).getDate()); @ @

prote&ted void setSeasonal-olor(Date date) : &alendar.set1ime(date); int month = &alendar.get(-alendar.MC$1<); J!ormatted1e t!ield 3t3 = get1e t!ield(dateSpinner); i3 (3t3 == n%ll) ret%rn; //Set the &olor to mat&h northern hemisphere seasonal &onventions. swit&h (month) : &ase 2B //Mar&h &ase EB ///pril &ase FB //Ma" 3t3.set!oregro%nd(S60>$?G-CLC0); #rea7; ... de3a%ltB //De&em#er( Jan%ar"( !e#r%ar" 3t3.set!oregro%nd(H>$1.0G-CLC0); @ @ ... @

The following example implements an editor which has a change listener so that it can reflect the spinner5s current value. This particular editor displa#s a solid color of gra#, ranging an#where from white to +lac3. $lic3 the *aunch +utton to run Spinner%emo> using Java9 4e+ Start 1download J%: ; or later2. 'lternativel#, to compile and run the example #ourself, consult the example index.

...//Where the components are created: JSpinner spinner = new JSpinner(new ?ra"Model(*I+)); spinner.set.ditor(new ?ra".ditor(spinner)); &lass ?ra"Model e tends Spinner$%m#erModel : ... @ &lass ?ra".ditor e tends JLa#el implements -hangeListener : p%#li& ?ra".ditor(JSpinner spinner) : setCpaJ%e(tr%e); ... //?et in3o 3rom the model. ?ra"Model m"Model = (?ra"Model)(spinner.getModel()); set5a&7gro%nd(m"Model.get-olor()); spinner.add-hangeListener(this); ... %pdate1ool1ip1e t(spinner); @ prote&ted void %pdate1ool1ip1e t(JSpinner spinner) : String tool1ip1e t = spinner.get1ool1ip1e t(); i3 (tool1ip1e t 9= n%ll) : //JSpinner has tool tip te t. Ase it. i3 (9tool1ip1e t.eJ%als(get1ool1ip1e t())) : set1ool1ip1e t(tool1ip1e t);

@ @ else : //De3ine o%r own tool tip te t. ?ra"Model m"Model = (?ra"Model)(spinner.getModel()); int rg# = m"Model.get>ntDal%e(); set1ool1ip1e t(4(4 , rg# , 4(4 , rg# , 4(4 , rg# , 4)4); @ @ p%#li& void state-hanged(-hange.vent e) : JSpinner m"Spinner = (JSpinner)(e.getSo%r&e()); ?ra"Model m"Model = (?ra"Model)(m"Spinner.getModel()); set5a&7gro%nd(m"Model.get-olor()); %pdate1ool1ip1e t(m"Spinner); @ @

The Spinner A !
The following ta+les list some of the commonl# used '() for using spinners. )f #ou need to deal directl# with the editor5s formatted text field, #ou should also see The FormattedTextField '(). ?ther methods #ou might use are listed in the '() ta+les in The J$omponent $lass.

$lasses @elated to Spinners seful JSpinner $onstructors and !ethods seful "ditor $onstructors and !ethods Spinner*ist!odel !ethods Spinner%ate!odel !ethods Spinner-um+er!odel !ethods Classes "elated to Spinners

Class or !nterface JSpinner Spinner!odel

urpose ' single6line input field that allows the user to select a num+er or o+ject value from an ordered se.uence. The interface implemented +# all spinner models. ' su+class of /#stra&tSpinnerModel whose values are defined +# an arra# or a List. ' su+class of /#stra&tSpinnerModel that supports se.uences of Date instances. ' su+class of /#stra&tSpinnerModel that supports se.uences of num+ers.

'+stractSpinner!odel The usual superclass for spinner model implementations. Spinner*ist!odel Spinner%ate!odel Spinner-um+er!odel

)mplements an unedita+le component that displa#s the JSpinner.%efault"ditor spinner5s value. Su+classes of this class are generall# more speciali,ed 1and edita+le2. JSpinner.*ist"ditor ' su+class of JSpinner.De3a%lt.ditor whose values are

defined +# an arra# or a List. JSpinner.%ate"ditor JSpinner.-um+er"ditor ' su+class of JSpinner.De3a%lt.ditor that supports se.uences of Date instances. ' su+class of JSpinner.De3a%lt.ditor that supports se.uences of num+ers. urpose $reates a new JSpinner. The no6argument constructor creates a spinner with an integer Spinner$%m#erModel with an initial value of A and no minimum or maximum limits. The optional parameter on the second constructor allows #ou to specif# #our own SpinnerModel. Sets or gets the currentl# displa#ed element of the se.uence. Bets the o+ject in the se.uence that comes +efore or after the o+ject returned +# the getDal%e method.

Useful #Spinner Constructors and Methods Constructor or Method

JSpinner12 JSpinner1Spinner!odel2

void set&alue1java.lang.?+ject2 ?+ject get&alue12 ?+ject get-ext&alue12 ?+ject get(revious&alue12

Spinner!odel get!odel12 Bets or sets the spinner5s model. void set!odel1Spinner!odel2 J$omponent get"ditor12 void set"ditor1J$omponent2 protected J$omponent create"ditor1Spinner!odel2 Bets or sets the spinner5s editor, which is often an o+ject of t#pe JSpinner.De3a%lt.ditor. $alled +# the JSpinner constructors to create the spinner5s editor. ?verride this method to associate an editor with a particular t#pe of model.

Useful Editor Constructors and Methods Constructor or Method urpose $reates a JSpinner.$%m#er.ditor instance that displa#s and allows editing of the num+er value of JSpinner.-um+er"ditor1JSpinner, the specified spinner. The string argument String2 specifies the format to use to displa# the num+er. See the '() documentation for %ecimalFormat for information a+out decimal format strings. $reates a JSpinner.Date.ditor instance that displa#s and allows editing of the Date value of the specified spinner. The string argument specifies the format to use to displa# the date. See the '() documentation for Simple%ateFormat for information a+out date format strings.

JSpinner.%ate"ditor1JSpinner, String2

JFormattedTextField getTextField12 (defined in


JSpinner.DefaultEditor)

Bets the formatted text field that provides the main B ) for this editor. Spinner$istModel Methods

Method

urpose

void set*ist1*ist2 Sets or gets the List that defines the se.uence for this model. *ist get*ist12 SpinnerDateModel Methods Method urpose

void set&alue1?+ject2 Sets or gets the current Date for this se.uence. %ate get%ate12 ?+ject get&alue12 void Sets or gets the first Date in this se.uence. se n%ll to specif# setStart1$ompara+le2 that the spinner has no lower limit. $ompara+le getStart12 void Sets or gets the last Date in this se.uence. se n%ll to specif# set"nd1$ompara+le2 that the spinner has no upper limit. $ompara+le get"nd12 Sets or gets the si,e of the date value increment used +# the get$e tDal%e and get6revio%sDal%e methods. This propert# is not used when the user explicitl# increases or decreases the valueC instead, the selected part of the formatted void text field is incremented or decremented. The specified set$alendarField1int2 parameter must +e one of the following constants, defined in int get$alendarField12 -alendar: .0/, './0, MC$1<, H..KGC!G'./0, H..KGC!GMC$1<, D/'GC!GMC$1<, D/'GC!G'./0, D/'GC!GH..K, D/'GC!GH..KG>$GMC$1<, /MG6M, <CA0GC!GD/', M>$A1., S.-C$D, M>LL>S.-C$D. SpinnerNum%erModel Methods Method void set&alue1?+ject2 -um+er get-um+er12 urpose Sets or gets the current value for this se.uence.

Sets or gets the upper +ound for num+ers in this void set!aximum1$ompara+le2 se.uence. )f the maximum is n%ll, there is no upper $ompara+le get!aximum12 +ound. void set!inimum1$ompara+le2 $ompara+le get!inimum12 void setStepSi,e1-um+er2 Sets or gets the lower +ound for num+ers in this se.uence. )f the minimum is n%ll, there is no lower +ound. Sets or gets the increment used +# get$e tDal%e and

-um+er getStepSi,e12

get6revio%sDal%e

methods.

E&amples That Use Spinners


This ta+le lists examples that use spinners and points to where those examples are descri+ed. E&ample
SpinnerDemo SpinnerDemo2 SpinnerDemoE SpinnerDemoF

'here Descri%ed This section This section This section This section

Notes ses all three standard spinner model classes. $ontains the code to use a custom spinner model, +ut the code is turned off +# default. ' SpinnerDemo su+class that uses the custom spinner model for its !onths spinner. 7ased on Spinner%emo, this application shows how to listen for changes in a spinner5s value. )mplements a custom model and a custom editor for a spinner that displa#s shades of gra#.

You might also like