Search code examples
javajavafx

JavaFX do something after property listener is activated


I have this code that saves TableView's TableColumn width size as preference:

column.widthProperty().addListener((obs, oldWidth, newWidth) -> {
            setTablePreference().saveColumnWidthSetting(newWidth.doubleValue(), column.getId().concat(columnWidthSettingsCommons.toString()));
        });

The code works as expected (whenever tableColumn width changes, it's automatically saved), but there's room for improvement. When resizing a tableColumn, this code runs hundreds of times due to the listener behavior, which is to listen for any and every change to tableColumn width.

Based on that, I have been wondering if there's a way to run this code only once, right after the listener stop running.

I thought of using a separate thread, but it creates hundreds of threads which by far is not what I'm trying to accomplish (which is performance):

column.widthProperty().addListener((obs, oldWidth, newWidth) -> {
            new Thread(new Task<>() {
                @Override
                protected Object call() {
                    setTablePreference().saveColumnWidthSetting(newWidth.doubleValue(), column.getId().concat(columnWidthSettingsCommons.toString()));
                    return null;
                }
            }).start();
        });

So my question is, is there a way to run a code after the listener has stopped listening for new values?


Solution

  • Following @James_D suggestion, I developed an implementation using PauseTransition:

    final PauseTransition columnWidthPropertyPauseTransition = new PauseTransition(Duration.seconds(0.5));
            column.widthProperty().addListener((obs, oldWidth, newWidth) -> {
                adjustNodePosition(tableView);
    
                if (columnWidthPropertyPauseTransition.getStatus() != Animation.Status.RUNNING)
                    columnWidthPropertyPauseTransition.play();
                columnWidthPropertyPauseTransition.setOnFinished(e -> setTablePreference().saveColumnWidthSetting(newWidth.doubleValue(), column.getId().concat(columnWidthSettingsCommons.toString())));
            });