问题
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.
回答1:
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.
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
来源:https://stackoverflow.com/questions/30780005/javafx-scrollpane-check-which-components-are-displayed