ScrollBar
In JavaFX, a ScrollBar is a control that allows users to scroll through content either vertically or horizontally. It’s different from ScrollPane because ScrollPane automatically handles scrolling for content, while ScrollBar is a standalone control you can use to manually track or control values.
Example: Simple ScrollBar
FXML (hello-view.fxml)
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.ScrollBar?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox spacing="10" alignment="CENTER"
xmlns="http://javafx.com/javafx/17"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="org.example.demo.HelloController">
<Label fx:id="valueLabel" text="Scroll Value: 0"/>
<ScrollBar fx:id="scrollBar" min="0" max="100" unitIncrement="1"/>
</VBox>
Controller (HelloController.java)
package org.example.demo;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollBar;
public class HelloController {
@FXML
private ScrollBar scrollBar;
@FXML
private Label valueLabel;
@FXML
public void initialize() {
// Listen for changes in the ScrollBar
scrollBar.valueProperty().addListener((obs, oldVal, newVal) -> {
valueLabel.setText("Scroll Value: " + newVal.intValue());
});
}
}
Key Points:
Orientation: By default, ScrollBar is vertical. You can make it horizontal:
<ScrollBar orientation="HORIZONTAL" ... />Properties:
min– Minimum valuemax– Maximum valuevalue– Current valueunitIncrement– Amount to scroll with arrow buttonsblockIncrement– Amount to scroll when clicking on the track
You can bind ScrollBar to control content manually or use it to show progress in custom components.