Как выполнить прокрутку, чтобы сделать Узел внутри содержимого ScrollPane видимым?
Учитывая, что огромный AnchorPane
с некоторыми подузлами является содержание ScrollPane
Как прокрутить, чтобы сделать один из подузлов, которые находятся за пределами текущего окна просмотра, видимым?
3 ответа
Вам нужно найти координаты этого внутреннего узла внутри content
и настроить ScrollPane
"s vValue
а также hValue
соответственно.
Увидеть ensureVisible()
Метод в следующем небольшом приложении:
public class ScrollPaneEnsureVisible extends Application {
private static final Random random = new Random();
private static void ensureVisible(ScrollPane pane, Node node) {
double width = pane.getContent().getBoundsInLocal().getWidth();
double height = pane.getContent().getBoundsInLocal().getHeight();
double x = node.getBoundsInParent().getMaxX();
double y = node.getBoundsInParent().getMaxY();
// scrolling values range from 0 to 1
pane.setVvalue(y/height);
pane.setHvalue(x/width);
// just for usability
node.requestFocus();
}
@Override
public void start(Stage primaryStage) {
final ScrollPane root = new ScrollPane();
final Pane content = new Pane();
root.setContent(content);
// put 10 buttons at random places with same handler
final EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
int index = random.nextInt(10);
System.out.println("Moving to button " + index);
ensureVisible(root, content.getChildren().get(index));
}
};
for (int i = 0; i < 10; i++) {
Button btn = new Button("next " + i);
btn.setOnAction(handler);
content.getChildren().add(btn);
btn.relocate(2000 * random.nextDouble(), 2000 * random.nextDouble());
}
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
// run once to don't search for a first button manually
handler.handle(null);
}
public static void main(String[] args) { launch(); }
}
Я создал немного более элегантную версию для этого случая. Тем не менее, я мог проверить только на оси у. Надеюсь, поможет
private static void ensureVisible(ScrollPane pane, Node node) {
Bounds viewport = scrollPane.getViewportBounds();
double contentHeight = scrollPane.getContent().localToScene(scrollPane.getContent().getBoundsInLocal()).getHeight();
double nodeMinY = node.localToScene(node.getBoundsInLocal()).getMinY();
double nodeMaxY = node.localToScene(node.getBoundsInLocal()).getMaxY();
double vValueDelta = 0;
double vValueCurrent = scrollPane.getVvalue();
if (nodeMaxY < 0) {
// currently located above (remember, top left is (0,0))
vValueDelta = (nodeMinY - viewport.getHeight()) / contentHeight;
} else if (nodeMinY > viewport.getHeight()) {
// currently located below
vValueDelta = (nodeMinY + viewport.getHeight()) / contentHeight;
}
scrollPane.setVvalue(vValueCurrent + vValueDelta);
}
Чтобы получить идеальную привязку, вам необходимо учитывать начальную и конечную позиции полосы прокрутки. Окно просмотра начинается с половины окна просмотра с 0(Bounds scollpane) и останавливается на половине окна просмотра с максимальной границей. границы и изображение в окне просмотра
Итак: узел Y ниже половины окна просмотра -> установите значение 0 на узел Y выше макс. половины окна просмотра -> установите значение 1
и между этим нам нужно вычислить общую высоту -1viewport (половина начала половина в конце) и узел y - половина окна просмотра. затем (узел y - половина окна просмотра) / (общая высота -1 просмотр)
double heightViewPort = scrollPane.getViewportBounds().getHeight();
double heightScrollPane = scrollPane.getContent().getBoundsInLocal().getHeight();
double y = Label.getBoundsInParent().getMaxY();
if (y<(heightViewPort/2)){
scrollPane.setVvalue(0);
// below 0 of scrollpane
}else if ((y>=(heightViewPort/2))&(y<=(heightScrollPane-heightViewPort/2))){
// between 0 and 1 of scrollpane
scrollPane.setVvalue((y-(heightViewPort/2))/(heightScrollPane-heightViewPort));
}
else if(y>= (heightScrollPane-(heightViewPort/2))){
// above 1 of scrollpane
scrollPane.setVvalue(1);
}