Slider
In JavaFX, a Slider is a control that allows users to select a numeric value by sliding a knob along a track. It can be horizontal or vertical and is often used for things like volume, brightness, or any numeric input within a range.
Example: Using a Slider
FXML (hello-view.fxml)
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.layout.VBox?>
<VBox spacing="15" alignment="CENTER"
xmlns="http://javafx.com/javafx/17"
xmlns:fx="http://javafx.com/fxml/1">
<Label text="Adjust Volume"/>
<Slider fx:id="volumeSlider"
min="0"
max="100"
value="50"
showTickLabels="true"
showTickMarks="true"
majorTickUnit="25"
minorTickCount="4"
blockIncrement="5"/>
<Label fx:id="volumeLabel" text="Volume: 50"/>
</VBox>
Controller (HelloController.java)
package org.example.demo;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
public class HelloController {
@FXML
private Slider volumeSlider;
@FXML
private Label volumeLabel;
@FXML
public void initialize() {
// Update label when slider moves
volumeSlider.valueProperty().addListener((obs, oldVal, newVal) -> {
volumeLabel.setText("Volume: " + newVal.intValue());
});
}
}
Key Features of Slider:
Range:
minandmaxproperties define the numeric range.Ticks:
showTickLabels→ shows numeric labels.showTickMarks→ shows tick marks along the track.majorTickUnit→ distance between major ticks.minorTickCount→ number of minor ticks between major ticks.
Orientation:
- Default is horizontal.
- Vertical example:
orientation="VERTICAL".
Block Increment: How much the slider changes when using keyboard arrows.