Javafx串联多个StringProperty

kal*_*gne 4 string javafx concatenation observable

有一种简单的方法来绑定StringProperty对象的串联吗?

这是我想要做的:

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() );
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Jam*_*s_D 11

你可以做:

s3.bind(Bindings.concat(s1, "  <some Text>  ", s2));
Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子:

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);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 你在`concat(...)`调用中使用了`+`我在哪里```? (3认同)
  • @BradTurek不是功能上的,但是`Bindings.concat(...)`是一个varargs方法,因此在这里更加方便(您需要`tf1.textProperty()。concat(“:”).concat(tf2.textProperty( ))`)。 (2认同)