我有一个 ScrollPane
,其中包含一个显示图像的 TilePane
。每当我删除其中一张图片时,ScrollPane
都会跳回顶部,这在尝试删除多张图片时非常烦人。有没有办法控制滚动行为?
我在 Windows 7 上运行这段代码:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;
public class ScrollbarProblem extends Application{
private TilePane imagePane;
private ScrollPane scroller;
@Override
public void start(Stage primaryStage) {
imagePane = new TilePane();
scroller = new ScrollPane();
scroller.setContent(imagePane);
BorderPane root = new BorderPane(scroller, null, null, null, null);
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
for(int i = 0; i < 20; i++){
Image img = new Image("https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/SIPI_Jelly_Beans_4.1.07.tiff/lossy-page1-220px-SIPI_Jelly_Beans_4.1.07.tiff.jpg");
final ImageView imageView = new ImageView(img);
final Button button = new Button("Delete");
final StackPane stackPane = new StackPane();
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
imagePane.getChildren().remove(stackPane);
}
});
stackPane.getChildren().addAll(imageView, button);
imagePane.getChildren().add(stackPane);
}
}
public static void main(String[] args) {
launch(args);
}
}
最佳答案
ScrollPane
确保聚焦的 Node
显示在视口(viewport)内。单击的 Button
具有焦点。这意味着焦点节点被移除并且 JavaFX 尝试将焦点移动到 ScrollPane
内容中的另一个节点,在本例中是第一个 Button
。 ScrollPane
将此节点滚动到 View 中,这解释了观察到的行为。
解决方案是将每个 Button
的 focusTraversable
属性设置为 false
。
仍然允许您通过 Tab 更改焦点的另一个选项是覆盖 ScrollPaneSkin
的 onTraverse
方法,因为这是负责此行为的方法:
scroller.setSkin(new ScrollPaneSkin(scroller) {
@Override
public void onTraverse(Node n, Bounds b) {
}
});
关于java - 删除节点时ScrollPane跳到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40983147/