Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX ScrollPane - Check which components are displayed

I wonder whether there is a ScrollPane property in JavaFX 8 that can be used to listen on the components that are currently displayed at a given time. For example, ScrollPane has a VBox which has 8 buttons. Only 4 buttons can be seen in scrollpane. I would like a listener that gives those 4 out of 8 buttons that are displayed while the position of the scroll changes.

like image 348
javasuns Avatar asked Jan 08 '23 04:01

javasuns


1 Answers

You can check if the Nodes visible like that:

private List<Node> getVisibleNodes(ScrollPane pane) {
    List<Node> visibleNodes = new ArrayList<>();
    Bounds paneBounds = pane.localToScene(pane.getBoundsInParent());
    if (pane.getContent() instanceof Parent) {
        for (Node n : ((Parent) pane.getContent()).getChildrenUnmodifiable()) {
            Bounds nodeBounds = n.localToScene(n.getBoundsInLocal());
            if (paneBounds.intersects(nodeBounds)) {
                visibleNodes.add(n);
            }
        }
    }
    return visibleNodes;
}

This method returns a List of all Visible Nodes. All it does is compare the Scene Coordinates of the ScrollPane and its Children.

enter image description here

If you want them in a Property just create your own ObservableList:

private ObservableList<Node> visibleNodes;

...

visibleNodes = FXCollections.observableArrayList();

ScrollPane pane = new ScrollPane();
pane.vvalueProperty().addListener((obs) -> {
    checkVisible(pane);
});
pane.hvalueProperty().addListener((obs) -> {
    checkVisible(pane);
});

private void checkVisible(ScrollPane pane) {
    visibleNodes.setAll(getVisibleNodes(pane));
}

For full Code see BitBucket

like image 90
Marcel Avatar answered Mar 05 '23 04:03

Marcel