gpt4 book ai didi

java - 自定义平移处理程序 Javafx

转载 作者:行者123 更新时间:2023-11-30 07:05:49 24 4
gpt4 key购买 nike

您好,由于 scrollpane 的内置平移工具存在问题(运行缓​​慢并且以 block 的形式过渡而不是流畅),我正在尝试创建一个自定义平移处理程序。以下是我的尝试,但 if 语句无法正常工作。

    mapScroll.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> {
startX = e.getX();
startY = e.getY();
});
mapScroll.addEventFilter(MouseEvent.MOUSE_DRAGGED, e -> {
endX = e.getX();
endY = e.getY();
Bounds viewBounds = mapScroll.getViewportBounds();
Bounds mapBounds = mapScroll.getBoundsInParent();
double xMin = viewBounds.getMinX();
double xMax = viewBounds.getMaxX();
double yMin = viewBounds.getMinY();
double yMax = viewBounds.getMaxY();
double startEndX = endX - startX;
double startEndY = endY - startY;
if(mapBounds.contains(xMin + startEndX, yMin + startEndY) && mapBounds.contains(xMin + startEndX, yMax + startEndY) && mapBounds.contains(xMax + startEndX, yMin + startEndY) && mapBounds.contains(xMax + startEndX, yMax + startEndY))
{
double fullWidth = mapScroll.getWidth();
double fullHeight = mapScroll.getHeight();
double hChange = startEndX/fullWidth;
double vChange = startEndY/fullHeight;
mapScroll.setHvalue(mapScroll.getHvalue() + hChange);
mapScroll.setVvalue(mapScroll.getVvalue() + vChange);
}
endX = startX;
endY = startY;
});

最佳答案

您永远不会在计算中使用内容的宽度。这意味着无论内容大小如何,您都必须将鼠标移动相同的距离才能从一侧滚动到另一侧直至底部。无论内容仅比视口(viewport)大 10 像素,还是内容是视口(viewport)大小的 10 倍,在代码中都没有区别。还要注意的是

endX = startX;
endY = startY;

绝对没用,因为无论如何,您都会覆盖事件过滤器每次调用开始时的值。您可能想以相反的方式完成作业。

您还可以按照与鼠标移动相同的方向移动滚动位置。但是,如果您希望鼠标位置相对于内容保持不变,则应该向相反方向移动滚动位置。

这是一个示例(为简单起见,删除了边界测试):

private double startX;
private double startY;

@Override
public void start(Stage primaryStage) {
ImageView image = new ImageView("https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/687px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg");
ScrollPane mapScroll = new ScrollPane(image);
Scene scene = new Scene(mapScroll, 400, 400);
mapScroll.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> {
startX = e.getX();
startY = e.getY();
});
mapScroll.addEventFilter(MouseEvent.MOUSE_DRAGGED, e -> {
double endX = e.getX();
double endY = e.getY();
Bounds viewBounds = mapScroll.getViewportBounds();

double startEndX = startX - endX;
double startEndY = startY - endY;

Bounds contentBounds = mapScroll.getContent().getLayoutBounds();

double hChange = startEndX / (contentBounds.getWidth() - viewBounds.getWidth());
double vChange = startEndY / (contentBounds.getHeight() - viewBounds.getHeight());
mapScroll.setHvalue(mapScroll.getHvalue() + hChange);
mapScroll.setVvalue(mapScroll.getVvalue() + vChange);

startX = endX;
startY = endY;
});

primaryStage.setScene(scene);
primaryStage.show();
}

关于java - 自定义平移处理程序 Javafx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40151586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com