Java Reference
In-Depth Information
L
ISTING
16.11
SliderDemo.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.Slider;
6
import
javafx.scene.layout.BorderPane;
7
import
javafx.scene.layout.Pane;
8
import
javafx.scene.text.Text;
9
10
public class
SliderDemo
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 Slider slHorizontal =
new
Slider();
16 slHorizontal.setShowTickLabels(
true
);
17 slHorizontal.setShowTickMarks(
true
);
18
19 Slider slVertical =
new
Slider();
20 slVertical.setOrientation(Orientation.VERTICAL);
21 slVertical.setShowTickLabels(
true
);
22 slVertical.setShowTickMarks(
true
);
23 slVertical.setValue(
100
);
24
25
// Create a text in a pane
26 Pane paneForText =
new
Pane();
27 paneForText.getChildren().add(text);
28
29
// Create a border pane to hold text and scroll bars
30 BorderPane pane =
new
BorderPane();
31 pane.setCenter(paneForText);
32 pane.setBottom(slHorizontal);
33 pane.setRight(slVertical);
34
35 slHorizontal.valueProperty().addListener(ov ->
36 text.setX(slHorizontal.getValue() * paneForText.getWidth() /
37 slHorizontal.getMax()));
38
39 slVertical.valueProperty().addListener(ov ->
40 text.setY((slVertical.getMax() - slVertical.getValue())
41 * paneForText.getHeight() / slVertical.getMax()));
42
43
// Create a scene and place it in the stage
44 Scene scene =
new
Scene(pane,
450
,
170
);
45 primaryStage.setTitle(
"SliderDemo"
);
// Set the stage title
46 primaryStage.setScene(scene);
// Place the scene in the stage
47 primaryStage.show();
// Display the stage
48 }
49 }
horizontal slider
set slider properties
vertical slider
set slider properties
add text to a pane
border pane
set new location for text
set new location for text
Slider
is similar to
ScrollBar
but has more features. As shown in this example, you can
specify labels, major ticks, and minor ticks on a
Slider
(lines 16-17).
A listener is registered to listen for the
slHorizontal value
property change (lines
35-37) and another one is for the
sbVertical value
property change (lines 39-41). When
the value of the slider changes, the listener is notified by invoking the handler to set a new posi-
tion for the text (lines 36-37, 40-41). Note that since the value of a vertical slider decreases
from top to bottom, the corresponding
y
value for the text is adjusted accordingly.
Search WWH ::
Custom Search