JavaFX 8:如何向侦听器添加时间延迟? [英] JavaFX 8: how to add a timedelay to a listener?

查看:181
本文介绍了JavaFX 8:如何向侦听器添加时间延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个JavaFX 8应用程序,我有一个tableView和一些textFields,可以搜索/过滤tableView中的某些列。我已经为textFields添加了一个监听器,以便在检测到更改时自动触发过滤。我使用下面的代码来执行此操作。

I'm working on an JavaFX 8 app right now, where i have a tableView and some textFields above which make it possible to search/filter for certain columns in the tableView. I have added a listener to the textFields, to trigger the filtering automatically when a change is detected. I used the code below to do this.

textField_filterAddress.textProperty().addListener((observable, oldValue, newValue) -> {
            doSomething(); // in this case, filter table data and refresh tableView afterwards
        });

我现在的问题是:
什么是集成某种时间延迟的最简单方法,在过滤被触发之前?我想等几毫秒,因为每次用户过滤它时都在执行一个新的数据库查询,我认为这对于用户输入的每个字符都不是必需的。我宁愿等到他/她完成了他的输入。
是否有某种类似的功能已经内置到整个侦听器中?或者我必须实施自己的解决方案?如果是这样,怎么样?我想到了某种并发解决方案,所以其他软件在等待期间不会冻结。但我以为我会问这里是否有一个更简单的解决方案,然后再考虑我自己的方式......

My question now is: what's the easiest way to integrate some kind of time delay, before the filtering gets triggered? I'd like to wait a few milliseconds, because everytime the user is filtering it's executing a new database query and i don't think this is necessary for every single char that the user puts in. I'd rather wait until he/she finished his input. Is there some kind of feature like this already built into the whole listener thing? Or do i have to implement my own solution? If so, how? I thought about some kind of concurrency solution, so the rest of the software won't freeze during the waiting period. But i thought i'd ask here if there is an easier solution before thinking too much about my own way...

提前非常感谢!

推荐答案

下面的代码将安排在文本字段最后一次更改后延迟1秒后执行某些操作。如果文本字段在该1秒窗口内发生变化,则忽略先前的更改,并计划使用新值从最近的更改开始1秒完成某事。

The code below will schedule to do something after a 1 second delay from the last time a text field changes. If the text field changes within that 1 second window, the previous change is ignored and the something is scheduled to be done with the new value 1 second from the most recent change.

PauseTransition pause = new PauseTransition(Duration.seconds(1));
textField.textProperty().addListener(
    (observable, oldValue, newValue) -> {
        pause.setOnFinished(event -> doSomething(newValue));
        pause.playFromStart();
    }
);

我没有测试过这个,但它应该有效: - )

I didn't test this, but it should work :-)

更复杂的解决方案可能是利用健忘 ReactFX可暂停事件流。基于ReactFX的解决方案在相关问题中讨论:

A more sophisticated solution might be to make use of a "forgetful" ReactFX suspendable event stream. ReactFX based solutions are discussed in the related question:

  • Wait before Reacting to a Property Change JavaFX 8

这篇关于JavaFX 8:如何向侦听器添加时间延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆