java - JavaFX binding between TextField and a property -
if create binding between javafx textfield , property, binding invalidated on every keystroke, causes change text.
if have chain of bindings default behavior cause problems, because in middle of editing values may not valid.
ok, know create uni-directional binding property textfield , register change listener informed when cursor leaves field , update property manually if necessary.
is there easy, elegant way change behavior binding invalidated when editing complete, e.g. when cursor leaves field?
thanks
i think you've pretty described way it. here's cleanest way can see implement (using java 8, though it's easy enough convert lambdas javafx 2.2 compatible if 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 \"%s\" \"%s\"%n", oldtext, newtext)); textfield tf2 = new textfield(); createcommitbinding(tf2).addlistener((obs, oldtext, newtext) -> system.out.printf("text 2 changed \"%s\" \"%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); } }
Comments
Post a Comment