How to add a ScrollBar in JavaFx

2019-02-19 03:24发布

问题:

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?

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

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.....

回答1:

I do not really get why you are trying to reinvent the wheel.. you should probably use the ScrollPane instead.

This little example shows how to create a horizontally scrollable HBox with the ScrollPane class:

@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();
}


回答2:

As eckig said, you can wrap you HBox into a 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