如何滚动以使ScrollPane内容内的Node可见? [英] How to scroll to make a Node within the content of a ScrollPane visible?
本文介绍了如何滚动以使ScrollPane内容内的Node可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于ScrollPane
的内容是一个巨大的AnchorPane
子节点,我该如何滚动以使其在当前视口之外的一个子节点可见?
Given that a huge AnchorPane
with some subnodes is the content of a ScrollPane
, how can i scroll to make one of the subnodes, that are outside of the current viewport, visible?
推荐答案
下一个示例中的代码比我的更为精确: https://stackoverflow.com/a/23518314/1054140
code in the next example is more precise than mine: https://stackoverflow.com/a/23518314/1054140
您需要在content
内部找到此内部节点的坐标,并相应地调整ScrollPane
的vValue
和hValue
.
You need to find a coordinates of this inner node inside content
and adjust ScrollPane
's vValue
and hValue
accordingly.
请参阅下一个小型应用程序中的ensureVisible()
方法:
See ensureVisible()
method in next small app:
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(); }
}
这篇关于如何滚动以使ScrollPane内容内的Node可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文