gpt4 book ai didi

JavaFX 滚动开始和结束

转载 作者:搜寻专家 更新时间:2023-11-01 02:59:17 38 4
gpt4 key购买 nike

我有一个非常昂贵的操作要在 Pane 上滚动鼠标。我目前使用

pane.setOnScroll({myMethod()}).

问题是,如果您滚动很多次,它会多次计算所有内容。所以我想要的是仅在滚动完成时执行我的操作。我希望使用 setOnScrollStarted,保存起始值并使用 setOnScrollFinished 来执行我的操作。

但我不知道为什么这两个方法从来没有被调用过。作为测试,我使用了

pane.setOnScroll({System.out.println("proof of action"});

而且它显然从未被调用过。

知道如何仅在滚动结束时调用我的方法吗?

提前致谢

最佳答案

来自javadoc of ScrollEvent (强调我的):

When the scrolling is produced by a touch gesture (such as dragging a finger over a touch screen), it is surrounded by the SCROLL_STARTED and SCROLL_FINISHED events. Changing number of involved touch points during the scrolling is considered a new gesture, so the pair of SCROLL_FINISHED and SCROLL_STARTED notifications is delivered each time the touchCount changes. When the scrolling is caused by a mouse wheel rotation, only a one-time SCROLL event is delivered, without the started/finished surroundings.

可能的解决方法:

每次检测到滚动时增加一个计数器变量。在监听器中启动一个等待 1 秒的新线程,仅当计数器等于 1(最后一次滚动)时才执行您想要的操作,然后递减计数器。

我创建了一个 Gist ,但我将代码复制到这里:

public class ScrollablePane extends Pane {
private Integer scrollCounter = 0;

private final ObjectProperty<EventHandler<? super ScrollEvent>> onScrollEnded = new SimpleObjectProperty<>();

public final ObjectProperty<EventHandler<? super ScrollEvent>> onScrollEndedProperty() {
return onScrollEnded;
}

public ScrollablePane() {
this.setOnScroll(e -> {
scrollCounter++;

Thread th = new Thread(() -> {
try {
Thread.sleep(1000);
if (scrollCounter == 1)
onScrollEnded.get().handle(e);

scrollCounter--;
} catch (Exception e1) {
e1.printStackTrace();
}
});
th.setDaemon(true);
th.start();
});
}

public void setOnScrollEnded(EventHandler<? super ScrollEvent> handler) {
onScrollEnded.setValue(handler);
}
}

使用方法:

public class MyApplication extends Application {


@Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 400, 400);

ScrollablePane pane = new ScrollablePane();
pane.setOnScrollEnded(e -> System.out.println("Scroll just has been ended"));

root.setCenter(pane);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
launch(args);
}
}

关于JavaFX 滚动开始和结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40843062/

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