我有一个滚动vbox,其中包含许多文本字段。我可以从一个Textfield到另一个Textfield。当我到达最后一个可见的最后一个选项卡时,Scrollpane切换到下一个"页面",并且光标位于新的最上面的Textfield中。
但是,我需要在可见区域底部从文本场跳到下一个时逐条滚动行为。
任何有想法的人。
package test;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Scroller extends Application {
@Override
public void start(Stage primaryStage) {
VBox vb = new VBox();
for (int i = 0; i < 360; i++) {
TextField x = new TextField(String.valueOf(i));
vb.getChildren().add(x);
}
ScrollPane sp = new ScrollPane(vb);
sp.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
sp.setFitToWidth(true);
TextField tf = new TextField();
HBox root = new HBox();
root.getChildren().addAll(sp, tf);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
可以确定内容坐标中顶部的坐标为
topY = (contentHeight - viewportHeight) * vValue
您可以将此公式和侦听器用于场景的focusedNode
属性,将聚焦节点的底部滚动到视口的底部:
public static boolean isChild(Parent parent, Node node) {
while (node != null && node != parent) {
node = node.getParent();
}
return parent == node;
}
@Override
public void start(Stage primaryStage) {
VBox vb = new VBox();
for (int i = 0; i < 360; i++) {
TextField x = new TextField(String.valueOf(i));
vb.getChildren().add(x);
}
ScrollPane sp = new ScrollPane(vb);
sp.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
sp.setFitToWidth(true);
TextField tf = new TextField();
HBox root = new HBox();
root.getChildren().addAll(sp, tf);
Scene scene = new Scene(root, 300, 250);
scene.focusOwnerProperty().addListener((o, oldVal, newVal) -> {
if (isChild(vb, newVal)) {
// get bounds of focused node in ScrollPane content
Bounds bounds = newVal.getLayoutBounds();
while (newVal != vb) {
bounds = newVal.localToParent(bounds);
newVal = newVal.getParent();
}
double h = vb.getHeight();
double vH = sp.getViewportBounds().getHeight();
// scroll node to bottom of the viewport if bottom is not in view
if (bounds.getMaxY() > sp.getVvalue() * (h - vH) + vH) {
sp.setVvalue((bounds.getMaxY() - vH) / (h - vH));
}
}
});
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}