Java Reference
In-Depth Information
A slider is a visual component that has a knob that can be moved to change a
value between a minimum and a maximum. The user drags the knob to a new
value or just clicks on any point on the slider bar to immediately move the knob
to this position and set the value accordingly.
We implement this slider as a control with a corresponding skin. The main
Slider
class contains variables to hold the
value
, along with
minimum
and
max-
imum
values. There are also two Boolean variables,
showLabels
and
showTicks
,
to control whether to show the minimum, current value, and maximum labels,
and whether to show the tick lines. Lastly, there is a variable,
snapTo
, that deter-
mines the rounding precision for the value. When the value is dragged or other-
wise set clicking on the slider bar, the value will be rounded to this precision.
The
Slider
class is shown in Listing 12.22.
Listing 12.22
Slider - Control
public class Slider extends Control {
public var
value
: Number;
public var
minimum
: Number = 0;
public var
maximum
: Number = 100;
public var
showTicks
: Boolean;
public var
showLabels
: Boolean;
public var
snapTo
: Number = 0.0;
init {
skin =
SliderSkin
{};
}
}
The
SliderSkin
class contains a rounded rectangle for the slider bar, a rectangle
for the knob, some lines for the tick marks, and some
Text
objects for the labels.
What is most interesting is how the drag operation works.
To make the drag work on the knob rectangle, you need to add functions for
mouse pressed, released, and dragged events. First, when the mouse is pressed,
we need to save the current horizontal location of the knob into the
saveX
vari-
able as a starting reference point for the drag. Another variable,
controlX
,
defines the current horizontal location of the knob, this is changed based on the
value
instance variable as a percentage of the
value
to the total value range.
Search WWH ::
Custom Search