Usability of JavaFX Properties outside the scope of the GUI view

前端 未结 3 1994
忘掉有多难
忘掉有多难 2020-12-05 19:27

After working some while with JavaFX (Java8) I had found the concept of Properties very useful, allowing to use bean compliant variables to be bound to update on changes usi

3条回答
  •  -上瘾入骨i
    2020-12-05 20:03

    Use change listeners instead of bindings. Here is a nice utility method for that:

    public  ChangeListener getFxListener(Consumer consumer) {
        return (observable, oldValue, newValue) -> {
            if (Platform.isFxApplicationThread()) {
                consumer.accept(newValue);
            }
            else {
                Platform.runLater(() -> consumer.accept(newValue));
            }
        };
    }
    

    Example usage in your controller:

    // domain object with JavaFX property members
    private User user;
    
    @FXML
    private TextField userName;
    
    @FXML
    protected void initialize() {
        user.nameProperty().addListener(getFxListener(this::setUserName));
    }
    
    public void setUserName(String value) {
        userName.setText(value);
    }
    

    I know that original poster mentioned that he cannot afford to use Platform.runLater but didn't specify why. If bindings were thread safe, they would be making this call under the hood anyways. There is no shortcut to thread safety, and these calls are served sequentially so they are safe to use.

提交回复
热议问题