⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 slider.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 3 页
字号:
            </span>            <div class=NavBit>                <a target=_top href=separator.html>&laquo;&nbsp;Previous</a>&nbsp;&bull;&nbsp;<a target=_top href=../TOC.html>Trail</a>&nbsp;&bull;&nbsp;<a target=_top href=spinner.html>Next&nbsp;&raquo;</a>            </div>            <div id=PageTitle>How to Use Sliders</div>            <blockquote>Use a<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JSlider.html"><code>JSlider</code></a> to let the user easily enter a numeric value boundedby a minimum and maximum value.If the ability to specify precise numbers is important,a slider can be coupled with a<a href="#ftf">formatted text field</a>.If space is limited,a <a href="spinner.html">spinner</a>is a possible alternative to a slider.<p>Here's a picture of an application that usesa slider to control animation speed:<p><center><IMG SRC="../../figures/uiswing/components/SliderDemo.png" WIDTH="268" HEIGHT="295" ALIGN="BOTTOM" ALT="A snapshot of SliderDemo, which uses a slider"></center></p><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/SliderDemo.jnlp">Run SliderDemo</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#SliderDemo">example index</a>.<li> Use the slider to adjust the animation speed.<li> Push the slider to 0 to stop the animation.</ol><hr></blockquote>Below is the code from<a class="SourceLink" target="_blank" href="examples/SliderDemo.java"><code>SliderDemo.java</code></a>that creates the slider in the previous example.<blockquote><pre>static final int FPS_MIN = 0;static final int FPS_MAX = 30;static final int FPS_INIT = 15;    //initial frames per second. . .JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,                                      FPS_MIN, FPS_MAX, FPS_INIT);framesPerSecond.addChangeListener(this);//Turn on labels at major tick marks.framesPerSecond.setMajorTickSpacing(10);framesPerSecond.setMinorTickSpacing(1);framesPerSecond.setPaintTicks(true);framesPerSecond.setPaintLabels(true);</pre></blockquote>By default, spacing for major and minor tick marks is zero.To see tick marks, you must explicitly set the spacing for eithermajor or minor tick marks (or both) to a non-zero valueand call <code>setPaintTicks(true)</code>.Just calling <code>setPaintTicks(true)</code> is not enough.To display standard, numeric labels at major tick mark locations,set the major tick spacing, then call <code>setPaintLabels(true)</code>.The example program provides labels for its slider this way.But you don't have to settle for these labels.<a href="#labels">Customizing Labels on a Slider</a>shows you how to customize slider labels.<p>When you move the slider's knob, the <code>stateChanged</code> method of theslider's <code>ChangeListener</code> is called.For information about change listeners,refer to <a href="../events/changelistener.html">How to Write a Change Listener</a>.Here is the change listener code that reacts to slider value changes:<blockquote><pre>public void stateChanged(ChangeEvent e) {    JSlider source = (JSlider)e.getSource();    if (!source.getValueIsAdjusting()) {        int fps = (int)source.getValue();        if (fps == 0) {            if (!frozen) stopAnimation();        } else {            delay = 1000 / fps;            timer.setDelay(delay);            timer.setInitialDelay(delay * 10);            if (frozen) startAnimation();        }    }}</pre></blockquote>Notice that our <code>stateChanged</code> methodchanges the animation speed only if <code>getValueIsAdjusting</code>returns <code>false</code>.Many change events are firedas the user moves the slider knob.This program is interested onlyin the final result of the user's action.</blockquote><h3><a name="labels">Customizing Labels on a Slider</a></h3><blockquote>Shown below is a modified version of the previous programthat uses a slider with custom labels:<p><center><IMG SRC="../../figures/uiswing/components/SliderDemo2.png" WIDTH="334" HEIGHT="254" ALIGN="BOTTOM" ALT="A snapshot of SliderDemo2, which uses a slider with custom labels"></center></p><p align=center></p>The source for this program is in<a class="SourceLink" target="_blank" href="examples/SliderDemo2.java"><code>SliderDemo2.java</code></a>.You can<a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/SliderDemo2.jnlp"><b>run SliderDemo2</b></a> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.    Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#SliderDemo2">example index</a>.<p>The following code creates the slider and customizes its labels:<blockquote><pre>//Create the sliderJSlider framesPerSecond = new JSlider(JSlider.VERTICAL,                                      FPS_MIN, FPS_MAX, FPS_INIT);framesPerSecond.addChangeListener(this);framesPerSecond.setMajorTickSpacing(10);framesPerSecond.setPaintTicks(true);//Create the label tableHashtable labelTable = new Hashtable();labelTable.put( new Integer( 0 ), new JLabel("Stop") );labelTable.put( new Integer( FPS_MAX/10 ), new JLabel("Slow") );labelTable.put( new Integer( FPS_MAX ), new JLabel("Fast") );framesPerSecond.setLabelTable( labelTable );framesPerSecond.setPaintLabels(true);</pre></blockquote>Each key-value pair in the hashtablespecified with <code>setLabelTable</code>gives the position and the value of one label.The hashtable key must be an <code>Integer</code>and a value within the slider's range at which to place the label.The hashtable valueassociated with each keymust be a <code>Component</code>.This program uses <code>JLabel</code> instances with text only.An interesting variation would be to use<code>JLabel</code> instances with icons,or perhaps buttons that move the knob to the label's position.<p>If you want a set of numeric labels positionedat a specific interval, you can use <code>JSlider</code>'s<code>createStandardLabels</code> method tocreate the <code>Hashtable</code> for you.You can also modify the table returnedby <code>createStandardLabels</code> to then customize it.</blockquote><h3><a name="ftf">Using a Formatted Text Field with a Slider</a></h3><blockquote>Often, a slider is paired with a text fieldso that the user can enter a precise value.SliderDemo3 adds a formatted text field to SliderDemo,tying the text field's value to that of the slider.You can<a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/SliderDemo3.jnlp"><b>run SliderDemo3</b></a> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.Or, to compile and run the example yourself,consult the<a href="examples/index.html#SliderDemo3">example index</a>.<p><center><IMG SRC="../../figures/uiswing/components/SliderDemo3.png" WIDTH="268" HEIGHT="305" ALIGN="BOTTOM" ALT="A snapshot of SliderDemo3, which uses a slider with a text field"></center></p><p>The next few code snippets show the code in<a class="SourceLink" target="_blank" href="examples/SliderDemo3.java"><code>SliderDemo3.java</code></a> that supports the formatted text field.If you find it hard to understand,you might want to visit the<a href="formattedtextfield.html">Using Formatted Text Fields</a>page.<p>The following snippetcreates the text fieldand its formatter.Note that the formatter is created using aninteger <code>NumberFormat</code>,and that the number formatter's minimum and maximumare set to the same values used for the slider.<blockquote><pre>JFormattedTextField textField;...<em>//Where the components are created:</em>java.text.NumberFormat numberFormat =    java.text.NumberFormat.getIntegerInstance();NumberFormatter formatter = new NumberFormatter(numberFormat);formatter.setMinimum(new Integer(FPS_MIN));formatter.setMaximum(new Integer(FPS_MAX));textField = new JFormattedTextField(formatter);textField.setValue(new Integer(FPS_INIT));textField.setColumns(5); //get some space</pre></blockquote>The rest of the code we'll show you sets up the event handlingfor the text field.But first, you need to knowthat changing a formatted text field's <em>text</em> property(which always holds data of type <code>String</code>)doesn't directly change the formatted text field's <em>value</em> property(which, in this example, is a <code>Number</code>).The value property is set only aftera method called <code>commitEdit</code> is invokedon the text field,which typically happens when the text field contains valid textand either the user presses Enteror the text field loses focus.<p>The following code creates a key binding for the Enter keyso that whenever the userputs valid text in the text field and presses Enter,the text field's <em>value</em> (a <code>Number</code>) is set accordingly.(If the text is invalid, the system beepsand selects all the text.)The key binding is createdby adding entries to the text field's input and action maps.More information on input and action maps is in<a class="TutorialLink" target="_top" href="../misc/keybinding.html">How to Use Key Bindings</a>.<blockquote><pre>textField.getInputMap().put(KeyStroke.getKeyStroke(                                KeyEvent.VK_ENTER, 0),                                "check");textField.getActionMap().put("check", <em>anAction</em>);...<em>//Where anAction is implemented (as a subclass of AbstractAction):</em>public void actionPerformed(ActionEvent e) {    if (!textField.isEditValid()) { //The text is invalid.        Toolkit.getDefaultToolkit().beep();        textField.selectAll();    } else try {                    //The text is valid,        textField.commitEdit();     //so use it.    } catch (java.text.ParseException exc) { }}</pre></blockquote>The next snippet shows how we make the slider's valuechange whenever the text field's value changes.Recall that <code>framesPerSecond</code> is the variablethat refers to the <code>JSlider</code>.<blockquote><pre>textField.addPropertyChangeListener(this);...public void propertyChange(PropertyChangeEvent e) {    if ("value".equals(e.getPropertyName())) {        Number value = (Number)e.getNewValue();        if (framesPerSecond != null && value != null) {            framesPerSecond.setValue(value.intValue());        }    }}</pre></blockquote>Finally, adding bit of code to the slider's change listenerupdates the formatted text fieldwhenever the slider's value changes.While the user is dragging the slider,we update the text field's <em>text</em> &#151;not its <em>value</em> &#151;to prevent the text field's property change listenerfrom trying to update the slider(which might then try to update the text field,which would try to update the slider, and so on,in an unnecessary and perhaps unending cycle).Once the user has finished dragging the slider,we update the text field's <em>value</em>.<blockquote><pre>public void stateChanged(ChangeEvent e) {    JSlider source = (JSlider)e.getSource();    int fps = (int)source.getValue();    if (!source.getValueIsAdjusting()) { //done adjusting        <b>textField.setValue(new Integer(fps)); //update ftf value</b>        ...    <b>} else { //value is adjusting; just set the text        textField.setText(String.valueOf(fps));</b>    }}</pre></blockquote>You have seen one possible way of implementinga text field tied to a slider.Other ways are possible, but keep the following rules in mind:<ul><li> Only one component (or, more precisely, only one data model)     should have the final say on the value.     In SliderDemo3,     only the slider     controls how fast the animation goes.     The text field just displays the slider's value     and allows the user a second way of setting the slider's value.<li> The value and text properties of a formatted text field     can have different types,     and the value property generally lags the text property     (until <code>commitEdit</code> is invoked).<li> You can detect when the text field's value property changes     (so you can update the slider's value, for example)     by registering a property change listener on the text field.<li> You can display the slider's current value in a text field     (or other component, such as a label)     by adding a line to the slider's change event handler     that invokes <code>setText</code> on the text field.     Once the slider's value has settled,     you should update the formatted text field's value     using <code>setValue</code>.</ul>For further information, see<a href="formattedtextfield.html">Using Formatted Text Fields</a>.</blockquote>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -