JavaFX binding between TextField and a property

会有一股神秘感。 提交于 2019-12-06 03:03:47

I think you've pretty much described the only way to do it. Here's about the cleanest way I can see to implement it (using Java 8, though it's easy enough to convert the lambdas back to be JavaFX 2.2 compatible if you need):

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.StringBinding;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

    public class CommitBoundTextField extends Application {

        @Override
        public void start(Stage primaryStage) {
            TextField tf1 = new TextField();
            createCommitBinding(tf1).addListener((obs, oldText, newText) -> 
                System.out.printf("Text 1 changed from \"%s\" to \"%s\"%n", oldText, newText));
            TextField tf2 = new TextField();
            createCommitBinding(tf2).addListener((obs, oldText, newText) -> 
                System.out.printf("Text 2 changed from \"%s\" to \"%s\"%n", oldText, newText));
            VBox root = new VBox(5, tf1, tf2);
            Scene scene = new Scene(root, 250, 100);
            primaryStage.setScene(scene);
            primaryStage.show();
        }

        private StringBinding createCommitBinding(TextField textField) {
            StringBinding binding = Bindings.createStringBinding(() -> textField.getText());
            textField.addEventHandler(ActionEvent.ACTION, evt -> binding.invalidate());
            textField.focusedProperty().addListener((obs, wasFocused, isFocused)-> {
                if (! isFocused) binding.invalidate();
            });
            return binding ;
        }

        public static void main(String[] args) {
            launch(args);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!