Java Reference
In-Depth Information
When the user changes the value of the scroll bar, it notifies the listener of the change. You
can register a listener on the scroll bar's
valueProperty
for responding to this change as
follows:
ScrollBar sb =
new
ScrollBar();
sb.valueProperty().addListener(ov -> {
System.out.println(
"old value: "
+ oldVal);
System.out.println(
"new value: "
+ newVal);
});
Listing 16.10 gives a program that uses horizontal and vertical scroll bars to move a text
displayed on a pane. The horizontal scroll bar is used to move the text to the left and the right,
and the vertical scroll bar to move it up and down. A sample run of the program is shown in
FigureĀ 16.23.
Text
Vertical scroll
bar
Horizontal scroll
bar
F
IGURE
16.23
The scroll bars move the message on a pane horizontally and vertically.
Here are the major steps in the program:
1. Create the user interface.
Create a
Text
object and place it in the center of the border pane. Create a vertical scroll
bar and place it on the right of the border pane. Create a horizontal scroll bar and place
it at the bottom of the border pane.
2. Process the event.
Create listeners to move the text according to the bar movement in the scroll bars upon
the change of the
value
property.
L
ISTING
16.10
ScrollBarDemo.java
1
import
javafx.application.Application;
2
import
javafx.stage.Stage;
3
import
javafx.geometry.Orientation;
4
import
javafx.scene.Scene;
5
import
javafx.scene.control.ScrollBar;
6
import
javafx.scene.layout.BorderPane;
7
import
javafx.scene.layout.Pane;
8
import
javafx.scene.text.Text;
9
10
public class
ScrollBarDemo
extends
Application {
11 @Override
// Override the start method in the Application class
12
public void
start(Stage primaryStage) {
13 Text text =
new
Text(
20
,
20
,
"JavaFX Programming"
);
14
15 ScrollBar sbHorizontal =
new
ScrollBar();
16 ScrollBar sbVertical =
new
ScrollBar();
17 sbVertical.setOrientation(Orientation.VERTICAL);
18
19
horizontal scroll bar
vertical scroll bar
// Create a text in a pane
Search WWH ::
Custom Search