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?
The concat () method appends one String to the end of another. This method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method. Just like the concat method the ‘+’ operator also performs the concatenation operation on the given operators.
An extension to property listening is property binding, a functionality that allows users to wire properties together so that they can be automatically updated based on one or more changes. On top of that, JavaFX provides support for extending bindings through Expression objects and Bindings objects.
There are 30 types of Property object in JavaFX, including the StringProperty, SimpleListProperty and ReadOnlyObjectProperty. Each property wraps an existing Java object, adding functionality for listening and binding. The SimpleDoubleProperty inherits from a significant part of the JavaFX bindings, properties and value packages.
Most of the JavaFX Property objects extend two key interfaces: ReadOnlyProperty<T> and WriteableValue<T>. Some of them don’t, though. JavaFX has 10 read-only properties, which extend ReadOnlyProperty<T>, but don’t extend WriteableValue<T>. JavaFX comes with ten in-built classes that make creating a property significantly easier.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With