Sams Teach Yourself Java 2 in 24 Hours

Sams Teach Yourself Java 2 in 24 Hours

By Rogers Cadenhead

Sliders

One of the easiest ways for a user to enter numeric input is by using a slider, a component that can be dragged from side to side or up and down.

Sliders are represented in Swing by the JSlider class. Figure 16.2 shows what a slider component looks like.

16fig02.gif

Figure 16.2 Displaying a slider component.

Sliders enable a number to be chosen from between a minimum and maximum range of values. These values can be displayed on a label that includes the minimum value, maximum value, and intermediate values (as shown later in Figure 16.3).

16fig03.gif

Figure 16.3 Choosing a color using slider components.

You can create a horizontal slider with one of the following constructors:

To create a vertical slider, you must use a constructor method with an additional argument—the orientation of the slider. This argument should be the class variables JSlider.VERTICAL or JSlider.HORIZONTAL.

The following statement creates a vertical slider that can be used to pick a number from 1 to 1,000:

JSlider guess = new JSlider(JSlider.VERTICAL, 1, 1000, 500); 

This slider starts with the caret—the part of the component used to select a number—at the 500 position.

To display a label for a slider, you must set up the information that the label will contain. Call the slider's setMajorTickSpacing( int ) and setMinorTickSpacing( int ) methods to determine how often a tick mark will be displayed on the label. Major ticks are displayed as a thicker line than minor ticks.

After you have set up how often tick marks will appear, call the slider's setPaintTicks( boolean ) method with true as the argument.

You can also display the numeric value of each major tick by calling the slider's

setPaintLabels( boolean ) method with true.

The following statements can be used to create the slider shown in Figure 16.2:

JSlider percentage = new JSlider(0, 100, 25); 
percentage.setMajorTickSpacing(10); 
percentage.setMinorTickSpacing(5); 
percentage.setPaintTicks(true); 
percentage.setPaintLabels(true); 

Share ThisShare This

Informit Network