编程语言
首页 > 编程语言> > JavaFX滚动开始和结束

JavaFX滚动开始和结束

作者:互联网

我在窗格上的鼠标滚动上执行了非常昂贵的操作.我目前正在使用

pane.setOnScroll({myMethod()}).

问题是,如果你滚动了很多次,它会多次计算.所以我想要的只是在滚动完成后才做我的动作.我希望使用setOnScrollStarted,保存起始值和setOnScrollFinished来执行我的操作.

但我不知道为什么从不调用这两种方法.作为我使用的测试

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

它显然从未被称为.

关于如何仅在滚动结束时调用我的方法的任何想法?

提前谢谢,A

解决方法:

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);
    }
}

标签:java,javafx,scrollpane
来源: https://codeday.me/bug/20190627/1309106.html