Slider Controls in JavaFX - dummies

Slider Controls in JavaFX

By Doug Lowe

A slider is a control in JavaFX that’s used to indicate a continuous range of values between a given minimum and maximum. A slider is rendered as a vertical or horizontal bar with a knob that the user can slide to indicate the desired value. A slider can also have tick marks and labels to indicate the intervals along the bar.

This figure shows a scene that resembles an audio equalizer with eight slider controls, each showing tick marks allowing values from 0 to 100. The labels beneath the sliders are not a part of the slider control; they are separate labels whose values are set by the OnAction event generated whenever the user moves one of the sliders.

Slider controls in JavaFX.
Slider controls in JavaFX.

To create the slider controls shown, create a helper method named makeSlider, which returns a VBox object that contains the slider control along with the text that displays its value.

The method accepts an int value that indicates the starting value for the slider. The slider itself uses the default minimum and maximum values of 0 and 100, although you can easily change those values by calling the setMin and setMax methods.

Here’s the code for the makeSlider method:

private VBox makeSlider(int value)
    Text text = new Text();
    text.setFont(new Font("sans-serif", 10));
    Slider s = new Slider();
        (observable, oldvalue, newvalue) ->
            int i = newvalue.intValue();
        } );
    VBox box = new VBox(10, s, text);
    box.setPadding(new Insets(10));
    return box;