java 如何在 JavaFx 中添加滚动条
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28037818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a ScrollBar in JavaFx
提问by Program-Me-Rev
I'm trying to add a ScrollBar to a HBox. The ScrollBar gets added, but I get no scrolling. How can I make it work?
我正在尝试将 ScrollBar 添加到 HBox。ScrollBar 被添加,但我没有滚动。我怎样才能让它工作?
public class ScrollableItems {
public void scrollableItems(HBox content) {
double height = 180;
ScrollBar sc = new ScrollBar();
content.getChildren().add(sc);
sc.setLayoutX(content.getWidth() - sc.getWidth());
sc.setMin(0);
sc.setOrientation(Orientation.VERTICAL);
sc.setPrefHeight(height);
sc.setMax(height * 2);
sc.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> ov,
Number old_val, Number new_val) {
content.setLayoutY(-new_val.doubleValue());
}
});
}
}
Add children to a HBox then pass it to scrollableItems(HBox content)
above to add a SCrollBar
将孩子添加到 HBox 然后将其传递给scrollableItems(HBox content)
上面以添加 SCrollBar
public HBox mainItemsWrapper() {
HBox scrollabelWrapper = new HBox();
scrollabelWrapper.setMaxHeight(180);
HBox entityDetailViewWrapper = new HBox();
entityDetailViewWrapper.getChildren().addAll(.....);
scrollabelWrapper.getChildren().add(entityDetailViewWrapper);
new ScrollableItems().scrollableItems(scrollabelWrapper);
return scrollabelWrapper;
}
Thank you all.....
谢谢你们.....
回答by eckig
I do not really get why you are trying to reinvent the wheel.. you should probably use the ScrollPane
instead.
我真的不明白你为什么要重新发明轮子……你应该ScrollPane
改用 。
This little example shows how to create a horizontally scrollable HBox with the ScrollPane
class:
这个小例子展示了如何使用ScrollPane
类创建一个水平滚动的 HBox :
@Override
public void start(Stage primaryStage) {
HBox hbox = new HBox();
Button b = new Button("add");
b.setOnAction(ev -> hbox.getChildren().add(new Label("Test")));
ScrollPane scrollPane = new ScrollPane(hbox);
scrollPane.setFitToHeight(true);
BorderPane root = new BorderPane(scrollPane);
root.setPadding(new Insets(15));
root.setTop(b);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
回答by Spotted
As eckig said, you can wrap you HBox into a ScrollPane.
正如 eckig 所说,您可以将 HBox 包装到ScrollPane 中。
Additionnaly, you can customize the visual part of the scrollbar in CSS. I found this link useful for the comprehension of the differents parts of a scrollbar: Customize ScrollBar via CSS
此外,您可以在 CSS 中自定义滚动条的可视部分。我发现此链接有助于理解滚动条的不同部分:通过 CSS 自定义滚动条