How to access the Scrollbars of a ScrollPane

2019-02-11 00:30发布

I'm trying to get some information about the ScrollBar components that are by standard included in a ScrollPane. Especially i'm interested in reading the height of the horizontal Scrollbar. How can i reference it?

标签: javafx-2
2条回答
乱世女痞
2楼-- · 2019-02-11 01:09

I think you can use the lookupAll() method of the Node class for find the scroll bars. http://docs.oracle.com/javafx/2/api/javafx/scene/Node.html#lookupAll(java.lang.String)

For example:

package com.test;

import java.util.Set;
import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPaneBuilder;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.stage.Stage;

public class JavaFxScrollPaneTest extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        String longString = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.";
        Text longText = TextBuilder.create().text(longString).build();

        ScrollPane scrollPane = ScrollPaneBuilder.create().content(longText).build();
        primaryStage.setScene(new Scene(scrollPane, 400, 100));
        primaryStage.show();

        Set<Node> nodes = scrollPane.lookupAll(".scroll-bar");
        for (final Node node : nodes) {
            if (node instanceof ScrollBar) {
                ScrollBar sb = (ScrollBar) node;
                if (sb.getOrientation() == Orientation.HORIZONTAL) {
                    System.out.println("horizontal scrollbar visible = " + sb.isVisible());
                    System.out.println("width = " + sb.getWidth());
                    System.out.println("height = " + sb.getHeight());
                }
            }
        }
    }
}
查看更多
甜甜的少女心
3楼-- · 2019-02-11 01:16

This not is the best pratice, but works,

private boolean determineVerticalSBVisible(final ScrollPane scrollPane) {
    try {
        final ScrollPaneSkin skin = (ScrollPaneSkin) scrollPane.getSkin();
        final Field field = skin.getClass().getDeclaredField("vsb");
        field.setAccessible(true);
        final ScrollBar scrollBar = (ScrollBar) field.get(skin);
        field.setAccessible(false);
        return scrollBar.isVisible();
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return false;
}

Use "hsb" for Horizontal ScrollBar.

Best Regards, Henrique Guedes.

查看更多
登录 后发表回答