Sliders





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 shows what a slider component looks like.

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

3. Choosing a color using slider components.


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

  • JSlider(int, int)— Create a slider with the specified minimum value and maximum value.

  • JSlider(int, int, int)— Create a slider with the specified minimum value, maximum value, and starting value.

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:


JSlider percentage = new JSlider(0, 100, 25);

percentage.setMajorTickSpacing(10);

percentage.setMinorTickSpacing(5);

percentage.setPaintTicks(true);

percentage.setPaintLabels(true);


Watch Out!

Like other Swing components, a slider should be set up completely before you add it to the content pane or any other container. Otherwise, it may not be displayed as intended, or might not be displayed at all.



     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows