JavaFX: Bind StringProperty with constant string prefix

a3po2.0 picture a3po2.0 · Jun 25, 2013 · Viewed 11.6k times · Source

I have a question to the bind functionality in JavaFX. What I want is to bind 2 string properties. But their values should not be equal.

Let's make me an example:

I have a StringProperty with represents the last opened project in my application.
The value is like "C:\temp\myProject.prj".
I want to show this path in the title of my window.
It's easy: stage.titleProperty().bind(lastprojectProperty());
But I don't want to show only the project path but also the application name,
e.g.: MyApplication 2.2.4 - C:\temp\myProject.prj.

It's possible to use the binding and add a constant prefix string? Or do I have use a ChangeListerner?

The solution with the ChangeListener has the problem with the initial values...

    final StringProperty path = new SimpleStringProperty("untitled");
    final StringProperty title = new SimpleStringProperty("App 2.0.0");

    path.addListener(new ChangeListener<String>()
  {
        @Override
        public void changed(ObservableValue<? extends String> ov, String t, String newValue)   
        {
            title.setValue("App 2.0.0 - " + newValue);
        }
  });                

    // My title shows "App 2.0.0" since there is now change event throws until now...
    // Of course I could call path.setValue("untitled"); 
    // And above path = new SimpleStringProperty("");
    System.out.println(title.getValue());

    // Now the title is correct: "App 2.0.0 - C:\temp\myProject.prj"
    path.setValue("C:\\temp\\myProject.prj");
    System.out.println(title.getValue());

Answer

agonist_ picture agonist_ · Jun 25, 2013

If you do something like that

StringProperty prop = new SimpleStringProperty();
StringProperty other = new SimpleStringProperty();

prop.bind(Bindings.concat("your prefix").concat(other));

your property will be bind with the prefix you want