簡體   English   中英

如何獲取 JavaFX 中 ScrollBar 的拇指值范圍?

[英]How to get thumb value range of ScrollBar in JavaFX?

例如,假設我們有一個滾動條,用於在某些應用程序上顯示/操作數據。 滾動條也有最小值、最大值和可見量。 但是根據滾動條值顯示的值的范圍有點令人困惑。

作為一個例子,這里是一個圖像

但它是根據滾動條拇指的不同邊計算的。

假設我需要顯示數據庫中的一些數據,最小值將是最小 ID,最大值也將是最大 ID。 並考慮我想顯示 100 個項目,我將在滾動條中將可見數量設置為 100。 滾動時如果scoolbar 的值等於1,從數據庫中獲取范圍就像將100(可見量)加1 一樣簡單,但是當值等於max 時這將不起作用。 所以這就是為什么我需要獲取滾動條拇指的值范圍,但是在查看滾動條源代碼時我找不到這個功能的實現。

如何獲取滾動條的拇指或可見值范圍的最小值和最大值?

ScrollBar指示位置,而不是范圍。 該位置可通過value屬性獲得。 visualAmount屬性確定滑塊的大小。

如果value == max則拇指位於最右/最底位置。 您的“拇指的max ”將超過max

因此,您應該確定要顯示多少項,並根據以下內容計算visibleAmountmax

max           = itemCount - displayedItems
visibleAmount = max * displayedItems / itemCount

ScrollPane的實現的示例:

@Override
public void start(Stage stage) {
    ScrollBar scrollBar = new ScrollBar();
    scrollBar.setOrientation(Orientation.VERTICAL);
    StackPane.setAlignment(scrollBar, Pos.CENTER_RIGHT);

    VBox container = new VBox();
    StackPane.setAlignment(container, Pos.TOP_LEFT);

    StackPane root = new StackPane(container, scrollBar);

    InvalidationListener listener = o -> {
        // adjust scrollbar properties on resize of root or content
        double rootHeight = root.getHeight();
        double contentHeight = container.getHeight();

        double max = Math.max(0, contentHeight - rootHeight);
        scrollBar.setMax(max);
        scrollBar.setVisibleAmount(max * rootHeight / contentHeight);
    };
    root.heightProperty().addListener(listener);
    container.heightProperty().addListener(listener);

    // move container up based on the scrollbar value
    container.translateYProperty().bind(scrollBar.valueProperty().negate());

    // generate some content
    for (int i = 0; i < 10; i++) {
        Rectangle rect = new Rectangle(100, 100, (i & 1) == 0 ? Color.BLACK : Color.LIGHTGRAY);
        container.getChildren().add(rect);
    }

    Scene scene = new Scene(root, 300, 300);
    stage.setScene(scene);
    stage.show();
}

答案很簡單。 讓滾動條的高度為 600,拇指的高度為 200。現在如果你減去拇指的高度並根據剩余高度(400)計算要滾動的值,那么就不需要從末尾抑制最大值。

是的,你需要使用一些條件,以便拇指不會超過大小。 在這里,拇指(200px)不應超過 400px 高度,否則用戶將看不到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM