如何在 JavaFX 中向图像添加滚动条?
滚动条包含一个拇指以及一个添加到可滚动面板的右侧和左侧按钮。使用此操作,可以向上和向下滚动附加到它的面板。
在 JavaFX 中,javafx.scene.control.ScrollBar 代表一个滚动条。您可以通过实例化此类来创建一个滚动条。通常,一个滚动条与其他控件(如 ScrollPane、ListView 等)相关联。
将 ScrollBar 设置为图像
名为 value 的属性指定滚动条表示的当前值,您可以使用 addListener() 方法为此属性添加一个侦听器。
要将滚动条附加到图像,请执行以下操作:
创建一个表示所需图像的 ImageView 对象。
创建一个面板来容纳图像视图,如滚动面板、vBox 等。
为滚动条的 value 属性添加一个侦听器。
根据滚动条的方向,使用滚动条的新值的负值设置布局面板的 X/Y 布局。
示例
public class ScrollBarActionExample extends Application {
public void start(Stage stage) throws FileNotFoundException {
//Label for education
Label label = new Label("Educational qualification:");
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
label.setFont(font);
//list View for educational qualification
ScrollBar scroll = new ScrollBar();
scroll.setMin(0);
scroll.setOrientation(Orientation.VERTICAL);
scroll.setPrefHeight(200);
scroll.setPrefWidth(20);
//creating the image object
InputStream stream = new FileInputStream("D:\images\elephant.jpg");
Image image = new Image(stream);
//Creating the image view
ImageView imageView = new ImageView();
//Setting image to the image view
imageView.setImage(image);
//Setting the image view parameters
imageView.setX(5);
imageView.setY(0);
imageView.setFitWidth(595);
imageView.setPreserveRatio(true);
//Adding the toggle button to the pane
VBox vBox = new VBox(5);
vBox.getChildren().addAll(imageView);
scroll.valueProperty().addListener((ObservableValue<? extends Number> ov, Number old_val, Number new_val) -> {
vBox.setLayoutY(-new_val.doubleValue());
});
//Setting the stage
Group root = new Group();
root.getChildren().addAll(vBox, scroll);
Scene scene = new Scene(root, 595, 200, Color.BEIGE);
stage.setTitle("Scroll Bar Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP