2013-06-25 81 views
8

我对JavaFX中的绑定功能有疑问。我想要的是绑定2个字符串属性。但是他们的价值观不应该是平等的。JavaFX:使用常量字符串前缀绑定StringProperty

让我们做我举一个例子:

我有一个StringProperty与代表我的应用程序的最后一个打开的项目。
该值类似于“C:\ temp \ myProject.prj”。
我想在窗口的标题中显示此路径。
这很容易:stage.titleProperty().bind(lastprojectProperty());
但我不希望只显示该项目的路径,而且应用程序的名称,
例如: - MyApplication的2.2.4 - C:\ TEMP \ myProject.prj。

可以使用绑定并添加一个常量前缀字符串?或者我有使用ChangeListerner?

用的ChangeListener解决方案与初始值问题...

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

回答

18

如果你做这样的事情

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

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

你的财产将与前缀绑定你想

+0

agonist_非常感谢!你很棒!这是我想要的exactyl !!!有用!没有ChangeListener就容易多了。 –

+0

没问题,JavaFX绑定真的很强大,你可以做所有你想要的东西 –