JavaFX:使用常量字符串前缀绑定StringProperty [英] JavaFX: Bind StringProperty with constant string prefix

查看:1645
本文介绍了JavaFX:使用常量字符串前缀绑定StringProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对JavaFX中的绑定功能有疑问。我想要的是绑定2个字符串属性。但是它们的值不应该相等。

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.

让我举一个例子:

我有一个表示StringProperty在我的应用程序中最后打开的项目。

值类似于C:\ temp \ myProject.prj。

我想在我的标题中显示此路径窗口。

很简单: stage.titleProperty()。bind(lastprojectProperty());

但我不知道想要只显示项目路径,还要显示应用程序名称,

例如:
MyApplication 2.2.4 - C:\ temp \ myProject.prj。

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.

可以使用绑定并添加常量前缀字符串吗?或者我是否使用ChangeListerner?

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

使用ChangeListener的解决方案存在初始值的问题...

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


推荐答案

如果你这样做

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

这篇关于JavaFX:使用常量字符串前缀绑定StringProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆