首页 > 解决方案 > ChangeListener 功能可通过时间延迟/或其他解决方案检查键入的值

问题描述

我正在寻找代码中的功能,以允许我在 simpleTextField 中输入全名几秒钟,我需要它,因为如果我输入例如:

  1. 我输入 R - 然后改变方法正在做它的任务
  2. 我输入 RR - 然后方法更改两次做同样的事情(我不想要)

那么让程序等待几秒钟的最佳方法是什么,这样我就有时间完全输入所需的值,然后方法将只执行一次

    simpleTextField.textProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {

       // some funtionality to do

     }

标签: javajavafx

解决方案


PauseTransition每次修改 的text属性时,使用从开始播放的 a TextField

以下代码在对 的最后一次修改完成后的 1 秒内TextField添加了 的内容:ListViewTextField.text

@Override
public void start(Stage primaryStage) throws Exception {
    TextField text = new TextField();

    ListView<String> list = new ListView<>();

    PauseTransition delay = new PauseTransition(Duration.seconds(1));
    delay.setOnFinished(evt -> {
        list.getItems().add(text.getText());
    });

    // restart delay every time the text is modified
    text.textProperty().addListener((o, oldValue, newValue) -> delay.playFromStart());

    VBox root = new VBox(text, list);

    Scene scene = new Scene(root);
    primaryStage.setScene(scene);
    primaryStage.show();
}

您可能希望向该anchor属性添加另一个侦听器以处理选择的更改。


推荐阅读