📄 spinner.html
字号:
<a href=../../index.html target=_top>Home Page</a> > <a href=../index.html target=_top>Creating a GUI with JFC/Swing</a> > <a href=index.html target=_top>Using Swing Components</a> </span> <div class=NavBit> <a target=_top href=slider.html>« Previous</a> • <a target=_top href=../TOC.html>Trail</a> • <a target=_top href=splitpane.html>Next »</a> </div> <div id=PageTitle>How to Use Spinners</div> <blockquote>Spinners are similar to<a class="TutorialLink" target="_top" href="combobox.html">combo boxes</a> and<a class="TutorialLink" target="_top" href="list.html">lists</a> in that they let the user choose one from a range of values.Like editable combo boxes, spinners generally allowthe user to type in a value.Unlike combo boxes, spinners don't have a drop-down listthat can cover up other components.Because spinners don't display possible values —only the current value is visible —spinners are often used instead ofcombo boxes or listswhen the set of possible values is extremely large.However, spinners should only be usedwhen the possible values and their sequenceare obvious.<p>A spinner is a compound component with threesubcomponents: two small buttons and an<em>editor</em>.The editor can be any <code>JComponent</code>,but by default is implementedas a panel that contains a<a href="formattedtextfield.html">formatted text field</a>.The spinner's possible and current valuesare managed by its <em>model</em>.<p>Here's a picture of an application named SpinnerDemothat has three spinners used to specify dates:<p><center><IMG SRC="../../figures/uiswing/components/SpinnerDemo.png" WIDTH="215" HEIGHT="134" ALIGN="BOTTOM" ALT="SpinnerDemo shows 3 kinds of spinners"></center></p>The code for the main class is in<a class="SourceLink" target="_blank" href="examples/SpinnerDemo.java"><code>SpinnerDemo.java</code></a>.The Month spinner displays the nameof the first month in the user's locale.The possible values for this spinnerare specified usingan array of strings.The Year spinner displays one of a range of integers,initialized to the current year.The Another Date spinner displays onein a range of <code>Date</code>s(initially the current date)in a custom formatthat shows just the month and year.You might notice that the edges of the Another Date spinnerlook different from those of the spinners above it.This is because the example customizes the border of boththat spinnerand the formatted text field inside it.<blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/SpinnerDemo.jnlp">Run SpinnerDemo</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java<sup><font size=-2>TM</font></sup> Web Start</a>. Or, to compile and run the example yourself, consult the <a href="examples/index.html#SpinnerDemo">example index</a>.<li> With the Month spinner, use the arrow buttonsor keys tocycle forward and backward through the possible values.<br>Note that the lowest value is the first month of the year(for example, January)and the highest is the last (for example, December).The exact values depend on your locale.Also note that the values do not cycle — you can'tuse the up-arrow button or key to gofrom December directly to January.This is because the standard spinner models don't support cycling.<li> Type in a valid month name for your locale —for example, July.<br>Note that the spinner automatically completes the month name.<li> Moving on to the Year spinner,try typing a year over 100 years ago —for example, 1800 —and then click or tab to move the focus out of the spinner.<br>Because this program restricts the spinner's modelto numbers within 100 years of the current year,1800 is invalid.When the focus moves out of the spinner,the displayed text changes back to the last valid value.<li> Moving to the Another Date spinner,use the arrow buttons or keys to change the date.<br>Note that, by default, the first part of the date —in this case, the month number — changes.You can change which part changes byclicking or using the arrow keys to move to another part of the date.</ol><hr></blockquote><p>To create a spinner,you generally create its modeland then pass the model into the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JSpinner.html">JSpinner</a> constructor.For example:<blockquote><pre>String[] monthStrings = getMonthStrings(); //get month namesSpinnerListModel monthModel = new SpinnerListModel(monthStrings);JSpinner spinner = new JSpinner(monthModel);</pre></blockquote>The rest of this section covers the following topics:<ul name><li> <a href="#standard">Using Standard Spinner Models and Editors</a><li> <a href="#format">Specifying Spinner Formatting</a><li> <a href="#model">Creating Custom Spinner Models and Editors</a><li> <a href="#change">Detecting Spinner Value Changes</a><li> <a href="#api">The Spinner API</a><li> <a href="#eg">Examples that Use Spinners</a></ul></blockquote><h3><a name="standard">Using Standard Spinner Models and Editors</a></h3><blockquote>The Swing API provides three spinner models:<dl><dt><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/SpinnerListModel.html">SpinnerListModel</a></dt><dd>A spinner model whose values are defined by an array of objects or a <code>List</code>. SpinnerDemo's Month spinner uses this model, initialized with an array derived from the value returned by the <code>getMonths</code> method of <code>java.text.DateFormatSymbols</code>. See<a class="SourceLink" target="_blank" href="examples/SpinnerDemo.java"><code>SpinnerDemo.java</code></a> for details.</dd></dt><dt><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/SpinnerNumberModel.html">SpinnerNumberModel</a></dt><dd>Supports sequences of numbers,which can be expressed as <code>double</code>s,<code>int</code>s,or <code>Number</code>s.You can specify the minimum and maximum allowable values,as well as the <em>step size</em> —the amount of each increment or decrement.The Year spinner uses this model,created with the following code:<blockquote><pre>SpinnerModel model = new SpinnerNumberModel(currentYear, //initial value currentYear - 100, //min currentYear + 100, //max 1); //step</pre></blockquote></dd><dt><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/SpinnerDateModel.html">SpinnerDateModel</a></dt><dd>Supports sequences of <code>Date</code> objects.You can specify the minimum and maximum dates,as well as the field(such as <code>Calendar.YEAR</code>)to increment or decrement.Note, however, that some look and feelsignore the specified field,and instead change the fieldthat appears selected.The Another Date spinner uses this model, created with the following code:<blockquote><pre>Date initDate = calendar.getTime();calendar.add(Calendar.YEAR, -100);Date earliestDate = calendar.getTime();calendar.add(Calendar.YEAR, 200);Date latestDate = calendar.getTime();model = new SpinnerDateModel(initDate, earliestDate, latestDate, Calendar.YEAR);</pre></blockquote></dd></dl><p>When you set the spinner's model,the spinner's editor is automatically set.The Swing API provides an editor classcorresponding to each of the three model classes listed above.These classes —<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JSpinner.ListEditor.html">JSpinner.ListEditor</a>,<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JSpinner.NumberEditor.html">JSpinner.NumberEditor</a>, and<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JSpinner.DateEditor.html">JSpinner.DateEditor</a> —are all subclasses of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JSpinner.DefaultEditor.html">JSpinner.DefaultEditor</a> that feature editable formatted text fields.If you use a model that doesn't have an editor associated with it,the editor is by defaulta <code>JSpinner.DefaultEditor</code> instancewith an uneditable formatted text field.</blockquote><h3><a name="format">Specifying Spinner Formatting</a></h3><blockquote><p>To change the formattingused in a standard spinner editor,you can create and set the editor yourself.Another approach,which requires a little more codebut gives you more options when using a default editor,is to get the editor's formatted text fieldand invoke methods on it.<p>The <code>JSpinner.NumberEditor</code>and <code>JSpinner.DateEditor</code> classeshave constructors that allow you tocreate an editor that formats its data a particular way.For example, the following codesets up the Another Date spinnerso that instead of using the default date format,which is long and includes the time,it shows just the month and yearin a compact way.<blockquote><pre>spinner.setEditor(new JSpinner.DateEditor(spinner, "MM/yyyy"));</pre></blockquote><blockquote><hr><strong>Note:</strong> You can play with date formats by<a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/ComboBoxDemo2.jnlp">running ComboBoxDemo2</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.More information about ComboBoxDemo2 is in the<a href="examples/index.html#ComboBoxDemo2">example index</a>.For information about format strings, see the<a class="TutorialLink" target="_top" href="../../i18n/format/index.html">Formatting</a> lesson of the Internationalization trail.Tables of number format characters are in the section<a class="TutorialLink" target="_top" href="../../i18n/format/numberpattern.html">Getting Started</a>.<hr></blockquote><p>If you wish to invoke methods directly on the formatted text field —to set its horizontal alignment, for example —you can get it using the<code>getTextField</code> methoddefined in <code>JSpinner.DefaultEditor</code>.Note that the Swing-provided editors aren'tthemselves formatted text fields.Instead, they're <code>JPanel</code>sthat containa formatted text field.Here is an example of getting and invoking methods onthe editor's formatted text field:<blockquote><pre>//Tweak the spinner's formatted text field.ftf = getTextField(spinner);if (ftf != null ) { ftf.setColumns(8); //specify more width than we need ftf.setHorizontalAlignment(JTextField.RIGHT);}...public JFormattedTextField getTextField(JSpinner spinner) { JComponent editor = spinner.getEditor(); if (editor instanceof JSpinner.DefaultEditor) { return ((JSpinner.DefaultEditor)editor).getTextField(); } else { System.err.println("Unexpected editor type: " + spinner.getEditor().getClass() + " isn't a descendant of DefaultEditor"); return null; }}</pre></blockquote></blockquote><h3><a name="model">Creating Custom Spinner Models and Editors</a></h3><blockquote>If the existing spinner models or editors don't meet your needs,you can create your own.<p>The easiest route to creating a custom spinner modelis to create a subclassof an existing <code>AbstractSpinnerModel</code> subclassthat already does most of what you need.An alternative is to implement your own classby extending<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/AbstractSpinnerModel.html"><code>AbstractSpinnerModel</code></a>,which implements the event notificationsrequired for all spinner models.<p>The following subclass of <code>SpinnerListModel</code>implements a spinner modelthat cycles through an array of objects.It also lets you specify a second spinner's modelto be updated whenever the cycle begins again.For example, if the array of objects is a list of months,the linked model could be for a spinner that displays the year.When the month flips over from December to January the year is incremented.Similarly, when the month flips back from January to Decemberthe year is decremented.<blockquote><pre>public class CyclingSpinnerListModel extends SpinnerListModel { Object firstValue, lastValue; SpinnerModel linkedModel = null;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -