JavaFX: Bind StringProperty with constant string prefix

允我心安 提交于 2019-12-05 15:31:39

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/17293250/javafx-bind-stringproperty-with-constant-string-prefix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!