JavaFX: Bind StringProperty with constant string prefix
Asked Answered
C

1

15

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());
Consequently answered 25/6, 2013 at 9:5 Comment(0)
P
25

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

Primacy answered 25/6, 2013 at 9:14 Comment(3)
agonist_ thank you very much! You're great! This is exactyl what I wanted!!! It works! Much easier without the ChangeListener.Consequently
No problems, JavaFX bindings are really powerfull, you can do probably everything you wantPrimacy
Bindings.concat has vargs. So you just could do: prop.bind(Bindings.concat("your prefix", other));Polaris

© 2022 - 2024 — McMap. All rights reserved.