如何在滚动条中添加标记

时间:2016-09-29 21:40:13

标签: javafx scrollbar javafx-8

我正在实施搜索功能,我想在表格视图的滚动条中突出显示匹配的位置。

有没有办法在JavaFX的滚动条中显示颜色标记?

1 个答案:

答案 0 :(得分:8)

如果您在第一次进行布局后可以访问ScrollBar,则可以将标记添加到曲目中:

public class ScrollBarMark {

    private final Rectangle rect;
    private final DoubleProperty position = new SimpleDoubleProperty();

    public ScrollBarMark() {
        rect = new Rectangle(5, 5, Color.RED.deriveColor(0, 1, 1, 0.5));
        rect.setManaged(false);
    }

    public void attach(ScrollBar scrollBar) {
        StackPane sp = (StackPane) scrollBar.lookup(".track");
        rect.widthProperty().bind(sp.widthProperty());
        sp.getChildren().add(rect);
        rect.layoutYProperty().bind(Bindings.createDoubleBinding(() -> {
            double height = sp.getLayoutBounds().getHeight();
            double visibleAmout = scrollBar.getVisibleAmount();
            double max = scrollBar.getMax();
            double min = scrollBar.getMin();
            double pos = position.get();
            double delta = max - min;

            height *= 1 - visibleAmout / delta;

            return height * (pos - min) / delta;
        },
                position,
                sp.layoutBoundsProperty(),
                scrollBar.visibleAmountProperty(),
                scrollBar.minProperty(),
                scrollBar.maxProperty()));
    }

    public final double getPosition() {
        return this.position.get();
    }

    public final void setPosition(double value) {
        this.position.set(value);
    }

    public final DoubleProperty positionProperty() {
        return this.position;
    }

    public void detach() {
        StackPane parent = (StackPane) rect.getParent();
        if (parent != null) {
            parent.getChildren().remove(rect);
            rect.layoutYProperty().unbind();
            rect.widthProperty().unbind();
        }
    }

}

现在这仅适用于垂直ScrollBar

@Override
public void start(Stage primaryStage) {
    ScrollBar scrollBar = new ScrollBar();
    scrollBar.setOrientation(Orientation.VERTICAL);

    scrollBar.setMax(100);
    scrollBar.setVisibleAmount(50);
    scrollBar.valueProperty().addListener((a,b,c) -> System.out.println(c));

    StackPane root = new StackPane();
    root.getChildren().add(scrollBar);

    Scene scene = new Scene(root, 200, 500);

    // do layout
    root.applyCss();
    root.layout();

    ScrollBarMark mark1 = new ScrollBarMark();
    ScrollBarMark mark2 = new ScrollBarMark();
    mark1.attach(scrollBar);
    mark2.attach(scrollBar);
    mark1.setPosition(50);
    mark2.setPosition(75);

    primaryStage.setScene(scene);
    primaryStage.show();
}