9

Is there a simple way to bind a concatenation of StringProperty objects?

Here is what I want to do:

TextField t1 = new TextField();
TextField t2 = new TextField();

StringProperty s1 = new SimpleStringProperty();
Stringproperty s2 = new SimpleStringProperty();
Stringproperty s3 = new SimpleStringProperty();

s1.bind( t1.textProperty() ); // Binds the text of t1
s2.bind( t2.textProperty() ); // Binds the text of t2

// What I want to do, theoretically :
s3.bind( s1.getValue() + " <some Text> " + s2.getValue() );

How can I do that?

kaligne
  • 3,098
  • 9
  • 34
  • 60

1 Answers1

18

You can do:

s3.bind(Bindings.concat(s1, "  <some Text>  ", s2));

Here's a complete example:

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


public class BindingsConcatTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextField tf1 = new TextField();
        TextField tf2 = new TextField();
        Label label = new Label();

        label.textProperty().bind(Bindings.concat(tf1.textProperty(), " : ", tf2.textProperty()));

        VBox root = new VBox(5, tf1, tf2, label);
        Scene scene = new Scene(root, 250, 150);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}
James_D
  • 201,275
  • 16
  • 291
  • 322
  • Well it seems it does not work. If I bind the StringProperty of a label, it displays : `StringProperty [bound, invalid] StringPropery [bound, invalid]` Changing the values of s1 and s2 does not change anything. – kaligne Aug 15 '14 at 13:14
  • Added a full example. (I'm using JDK 1.8.0_11, fwiw) – James_D Aug 15 '14 at 13:29
  • 3
    Did you use `+` where I had `,` inside the `concat(...)` call? – James_D Aug 15 '14 at 13:35
  • Yes I did.. (Hiding my shame). Thanks a lot, problem solved :) – kaligne Aug 15 '14 at 13:54
  • Is there a difference between `Bindings.concat` and `textProperty().concat`? – Brad Turek Mar 08 '18 at 15:07
  • 2
    @BradTurek Not functionally, but `Bindings.concat(...)` is a varargs method, so it's more convenient here (you would need `tf1.textProperty().concat(" : ").concat(tf2.textProperty())`). – James_D Mar 08 '18 at 15:11