Java Reference
In-Depth Information
Displaying Tick Marks Within a JSlider
The
JSlider
component allows you to add tick marks either below a horizontal slider or to the
right of a vertical slider. These tick marks allow a user to get a rough estimate of the slider's
value and scale. There can be both major and minor tick marks; the major ones are simply
drawn to be a little longer. Either or both can be displayed, as well as neither of them, which is
the default.
■
Note
Technically, a custom look and feel could place the tick marks anywhere. However, the system-
provided look and feel types place the ticks below or to the right.
To display the tick marks, you need to enable their painting with the
public void
setPaintTicks(boolean newValue)
method. When called with a setting of
true
, this method enables
the painting of minor and major tick marks. By default, the tick spacing for both types of tick
marks is set to zero. When either is set to zero, that particular tick type isn't displayed. Because both
are initially zero, you must change the value of either tick spacing to see any ticks. The
public
void setMajorTickSpacing(int newValue)
and
public void setMinorTickSpacing(int newValue)
methods both support this change.
To demonstrate, Figure 12-6 shows four sliders: one with no ticks, one with aesthetically
pleasing tick spacing, and two with unconventional tick spacing. It helps if the major tick
spacing is a multiple of the minor tick spacing (just as a ruler shows inches, half inches, quarter
inches, and so on with different tick lengths). In addition, the tick spacing shouldn't be so
narrow that the ticks look like a solid block.
Figure 12-6.
Four JSlider controls demonstrating tick marks
The source for the example in Figure 12-6 is shown in Listing 12-4. The top slider has no
ticks. The bottom slider has the aesthetically pleasing major/minor spacing, with minor ticks
at 5 units and major ones at 25 units. The left slider displays poor spacing with minor ticks at 6
and major ticks at 25. The right slider has minor ticks at each individual unit, resulting in
spacing that's much too tight.