Sliders

The easiest way to collect numeric input from a user is with 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.

Sliders enable a number to be chosen between minimum and maximum values. These values can be displayed on a label that includes the minimum value, maximum value, and intermediate values. An example you create later is shown in Figure 16.2.

Figure 16.2. Choosing a color using three slider components.

Image

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

JSlider()—Create a slider with a minimum of 0, maximum of 100, and starting value of 50.

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

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

To create a vertical slider, use a constructor with an additional first argument: the orientation of the slider. This argument should be the class variable JSlider.VERTICAL or JSlider.HORIZONTAL.

The following statement creates a vertical slider for 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 that selects a number—at the 500 position.

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

After you have set up how often tick marks appear, call the slider’s setPaintTicks(boolean) method with true as the argument. You also can display the numeric value of each major tick by calling the slider’s setPaintLabels(boolean) method with true.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.234.188