Documentation

The Java™ Tutorials
Hide TOC
How to Use Sliders如何使用滑块
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Use Sliders如何使用滑块

A JSlider component is intended to let the user easily enter a numeric value bounded by a minimum and maximum value. JSlider组件旨在让用户轻松输入由最小值和最大值限定的数值。If space is limited, a spinner is a possible alternative to a slider.如果空间有限,微调器是滑块的可能替代方案。

The following picture shows an application that uses a slider to control animation speed:下图显示了使用滑块控制动画速度的应用程序:

A snapshot of SliderDemo, which uses a slider

Try this: 
  1. Click the Launch button to run SliderDemo using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行SliderDemo(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引Launches the SliderDemo application
  2. Use the slider to adjust the animation speed.使用滑块调整动画速度。
  3. Push the slider to 0 to stop the animation.将滑块推到0以停止动画。

Below is the code from the SliderDemo.java file that creates the slider in the previous example.下面是在前面示例中创建滑块的SliderDemo.java文件中的代码。

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);

By default, spacing for major and minor tick marks is zero. 默认情况下,主刻度线和次刻度线的间距为零。To see tick marks, you must explicitly set the spacing for either major or minor tick marks (or both) to a non-zero value and call the setPaintTicks(true) method. 要查看刻度线,必须将主刻度线或次刻度线(或两者)的间距显式设置为非零值,并调用setPaintTicks(true)方法。However, you also need labels for your tick marks. 但是,您还需要标记记号的标签。To display standard, numeric labels at major tick mark locations, set the major tick spacing, then call the setPaintLabels(true) method. 要在主刻度标记位置显示标准数字标签,请设置主刻度间距,然后调用setPaintLabels(true)方法。The example program provides labels for its slider in this way. 示例程序以这种方式为其滑块提供标签。But you are not constrained to using only these labels. 但您不限于仅使用这些标签。Customizing Labels on a Slider shows you how to customize slider labels. 自定义滑块上的标签显示了如何自定义滑块标签。In addition, a slider feature allows you to set a font for the JSlider component.此外,滑块功能允许您为JSlider组件设置字体。

Font font = new Font("Serif", Font.ITALIC, 15);
framesPerSecond.setFont(font);

When you move the slider's knob, the stateChanged method of the slider's ChangeListener is called. 移动滑块的旋钮时,将调用滑块的ChangeListenerstateChanged方法。For information about change listeners, refer to How to Write a Change Listener. 有关更改侦听器的信息,请参阅如何编写更改侦听器Here is the change listener code that reacts to slider value changes:以下是对滑块值更改做出反应的更改侦听器代码:

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();
        }
    }
}

Notice that the stateChanged method changes the animation speed only if the getValueIsAdjusting method returns false. 请注意,只有当getValueIsAdjusting方法返回false时,stateChanged方法才会更改动画速度。Many change events are fired as the user moves the slider knob. 当用户移动滑块旋钮时,会触发许多更改事件。This program is interested only in the final result of the user's action.该程序只对用户操作的最终结果感兴趣。

Customizing Labels on a Slider自定义滑块上的标签

The demo below is a modified version of the SliderDemo that uses a slider with custom labels:下面的演示是SliderDemo的修改版本,使用带有自定义标签的滑块:

A snapshot of SliderDemo2, which uses a slider with custom labels

The source for this program can be found in SliderDemo2.java. 该程序的源代码可以在SliderDemo2.java中找到。Click the Launch button to run SliderDemo2 using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行SliderDemo2(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引

Launches the SliderDemo2 application

The following code creates the slider and customizes its labels:以下代码创建滑块并自定义其标签:

//Create the slider
JSlider framesPerSecond = new JSlider(JSlider.VERTICAL,
                                      FPS_MIN, FPS_MAX, FPS_INIT);
framesPerSecond.addChangeListener(this);
framesPerSecond.setMajorTickSpacing(10);
framesPerSecond.setPaintTicks(true);

//Create the label table
Hashtable 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);

Each key-value pair in the hashtable specified with the setLabelTable method gives the position and the value of one label. 使用setLabelTable方法指定的哈希表中的每个键值对都给出一个标签的位置和值。The hashtable key must be of an Integer type and must have a value within the slider's range at which to place the label. 哈希表键必须是Integer类型,并且必须在滑块的范围内有一个值来放置标签。The hashtable value associated with each key must be a Component object. 与每个键关联的哈希表值必须是Component对象。This demo uses JLabel instances with text only. 此演示使用仅包含文本的JLabel实例。An interesting modification would be to use JLabel instances with icons or buttons that move the knob to the label's position.一个有趣的修改是使用带有图标或按钮的JLabel实例,将旋钮移动到标签的位置。

Use the createStandardLabels method of the JSlider class to create a set of numeric labels positioned at a specific interval. 使用JSlider类的createStandardLabels方法创建一组以特定间隔定位的数字标签。You can also modify the table returned by the createStandardLabels method in order to customize it.您还可以修改createStandardLabels方法返回的表,以便对其进行自定义。

The Slider API滑块API

The following tables list the commonly used JSlider constructors and methods. 下表列出了常用的JSlider构造函数和方法。See The JComponent Class for tables of commonly used inherited methods.有关常用继承方法的表,请参阅JComponent

The API for using sliders is divided into these categories:使用滑块的API分为以下几类:

Creating the Slider创建滑块
Constructor建造师 Purpose目的
JSlider() Creates a horizontal slider with the range 0 to 100 and an initial value of 50.创建范围为0到100、初始值为50的水平滑块。
JSlider(int min, int max)
JSlider(int min, int max, int value)
Creates a horizontal slider with the specified minimum and maximum values. 使用指定的最小值和最大值创建水平滑块。The third int argument, when present, specifies the slider's initial value.第三个int参数(如果存在)指定滑块的初始值。
JSlider(int orientation)
JSlider(int orientation, int min, int max, int value)
Creates a slider with the specified orientation, which must be either JSlider.HORIZONTAL or JSlider.VERTICAL. 创建具有指定方向的滑块,该方向必须是JSlider.HORIZONTALJSlider.VERTICALThe last three int arguments, when present, specify the slider's minimum, maximum, and initial values, respectively.最后三个int参数(如果存在)分别指定滑块的最小值、最大值和初始值。
JSlider(BoundedRangeModel) Creates a horizontal slider with the specified model, which manages the slider's minimum, maximum, and current values and their relationships.使用指定的模型创建水平滑块,该模型管理滑块的最小值、最大值和当前值及其关系。
Fine Tuning the Slider's Appearance微调滑块的外观
Method方法 Purpose目的
void setValue(int)
int getValue()
Sets or gets the slider's current value. The set method also positions the slider's knob.设置或获取滑块的当前值。设置方法还可以定位滑块的旋钮。
void setOrientation(int)
int getOrientation()
Sets or gets the orientation of the slider. 设置或获取滑块的方向。Possible values are JSlider.HORIZONTAL or JSlider.VERTICAL.可能的值是JSlider.HORIZONTALJSlider.VERTICAL
void setInverted(boolean)
boolean getInverted()
Sets or gets whether the maximum is shown at the left of a horizontal slider or at the bottom of a vertical one, thereby inverting the slider's range.设置或获取最大值是显示在水平滑块的左侧还是垂直滑块的底部,从而反转滑块的范围。
void setMinimum(int)
int getMinimum()
void setMaximum(int)
int getMaximum()
Sets or gets the minimum or maximum values of the slider. 设置或获取滑块的最小值或最大值。Together, these methods set or get the slider's range.这些方法一起设置或获取滑块的范围。
void setMajorTickSpacing(int)
int getMajorTickSpacing()
void setMinorTickSpacing(int)
int getMinorTickSpacing()
Sets or gets the range between major and minor ticks. 设置或获取主刻度和次刻度之间的范围。You must call setPaintTicks(true) for the tick marks to appear.必须调用setPaintTicks(true)才能显示记号。
void setPaintTicks(boolean)
boolean getPaintTicks()
Sets or gets whether tick marks are painted on the slider.设置或获取是否在滑块上绘制刻度线。
void setPaintLabels(boolean)
boolean getPaintLabels()
Sets or gets whether labels are painted on the slider. 设置或获取是否在滑块上绘制标签。You can provide custom labels with setLabelTable or get automatic labels by setting the major tick spacing to a non-zero value.您可以提供使用setLabelTable的自定义标签,或者通过将主刻度间距设置为非零值来获取自动标签。
void setLabelTable(Dictionary)
Dictionary getLabelTable()
Sets or gets the labels for the slider. 设置或获取滑块的标签。You must call setPaintLabels(true) for the labels to appear.必须调用setPaintLabels(true)才能显示标签。
Hashtable createStandardLabels(int)
Hashtable createStandardLabels(int, int)
Creates a standard set of numeric labels. 创建一组标准的数字标签。The first int argument specifies the increment, the second int argument specifies the starting point. 第一个int参数指定增量,第二个int参数指明起点。When left unspecified, the starting point is set to the slider's minimum number.未指定时,起点设置为滑块的最小值。
setFont(java.awt.Font) Sets the font for slider labels .设置滑块标签的字体。
Watching the Slider Operate观看滑块操作
Method方法 Purpose目的
void addChangeListener(ChangeListener) Registers a change listener with the slider.使用滑块注册更改侦听器。
boolean getValueIsAdjusting() Determines whether the user gesture to move the slider's knob is complete.确定移动滑块旋钮的用户手势是否完成。
Working Directly with the Data Model直接使用数据模型
Class, Interface, or Method类、接口或方法 Purpose目的
BoundedRangeModel The interface required for the slider's data model.滑块数据模型所需的接口。
DefaultBoundedRangeModel An implementation of the BoundedRangeModel interface.BoundedRangeModel接口的实现。
void setModel()
getModel()
(in JSlider)
Sets or gets the data model used by the slider. 设置或获取滑块使用的数据模型。You can also set the model by using the constructor that takes a single argument of type BoundedRangeModel.您还可以使用构造函数来设置模型,该构造函数接受BoundedRangeModel类型的单个参数。

Examples that Use Sliders使用滑块的示例

This table shows the examples that use JSlider and where those examples are described.下表显示了使用JSlider的示例以及这些示例的描述位置。

Example示例 Where Described描述位置 Notes备注
SliderDemo This section本节 Shows a slider with labels at major tick marks.在主刻度处显示带有标签的滑块。
SliderDemo2 This section本节 Shows a vertical slider with custom labels.显示带有自定义标签的垂直滑块。
Converter Using Models使用模型, How to Use Panels如何使用面板 A measurement conversion application featuring two sliders that share data and have custom BoundedRangeModels.一个测量转换应用程序,具有两个共享数据并具有自定义BoundedRangeModel的滑块。

If you are programming in JavaFX, see Slider.如果您使用JavaFX编程,请参阅滑块


Previous page: How to Use Separators
Next page: How to Use Spinners