Apr 28, 2017

JavaFX Controls: ScrollBar

The ScrollBar control in JavaFX is not usually used by itself; instead, it is used by other controls such as ScrollPane or ListView to display the scroll bar that lets the user scroll the contents of a panel or other region.

However, there are occasions when you might want to use a scroll bar for some purpose other than scrolling a region. In fact, you can actually use a scroll bar in much the same way as you use a slider, as the two are very similar.

One difference is that unlike a slider, a scroll bar does not allow tick marks. But on the other hand, a scroll bar has increment and decrement buttons on either end of the bar, which allows the user to set the scroll bar’s value up or down in fixed increments.

This figure shows a version of an audio mixer, only implemented with scroll bars. As in the slider version, each scroll bar is paired with a Text object that displays the scroll bar’s value whenever the user manipulates the control.

You can use the following helper method to create each combined scroll bar and Text object:

Using JavaFX scroll bars to create a mixer board.
Using JavaFX scroll bars to create a mixer board.
private Node makeScrollBar(int value){    Text text = new Text();    text.setFont(new Font("sans-serif", 10));    ScrollBar sb = new ScrollBar();    sb.setOrientation(Orientation.VERTICAL);    sb.setPrefHeight(150);    sb.valueProperty().addListener(        (observable, oldvalue, newvalue) ->        {            int i = newvalue.intValue();            text.setText(Integer.toString(100-i));        }        );    sb.setValue(value);    VBox box = new VBox(10, sb, text);    box.setPadding(new Insets(10));    box.setAlignment(Pos.CENTER);    box.setMinWidth(30);    box.setPrefWidth(30);    box.setMaxWidth(30);    return box;}