2015-03-13 56 views
0

我有一个标签和一个双重属性。我想输出后缀“$”,我的价值。即“200.50 $”。我怎样才能用JavaFX做到这一点?我想过使用这样的绑定:如何使用格式化程序绑定属性

@FXML Label label; 
DoubleProperty value; 
... 
Bindings.bindBidirectional(label.textProperty(), valueProperty(), NumberFormat.getInstance()); 

但是还没有找到一种方法来将“$”附加到文本中。

非常感谢您的帮助!

+0

心不是有什么样Bindings.format( “%d $” 的PropertyValue) ; ? – NDY 2015-03-13 08:57:32

回答

1

感谢ItachiUchiha和NDY,我找到了正确的方向。我将不得不使用像这样的字符串转换:

public class MoneyStringConverter extends StringConverter<Number> { 

    String postFix = " $"; 
    NumberFormat formatter = numberFormatInteger; 

    @Override 
    public String toString(Number value) { 

     return formatter.format(value) + postFix; 

    } 

    @Override 
    public Number fromString(String text) { 

     try { 

     // we don't have to check for the symbol because the NumberFormat is lenient, ie 123abc would result in the value 123 
     return formatter.parse(text); 

     } catch(ParseException e) { 
     throw new RuntimeException(e); 
     } 

    } 

    } 

,然后我可以在使用它的绑定:

Bindings.bindBidirectional(label.textProperty(), valueProperty(), new MoneyStringConverter()); 
+0

我仍然认为,这种方法不是很好(对于单向绑定)。我更喜欢'label.textProperty()。bind(doubleProperty()。asString(“%。2f”));' - 更短,更容易阅读。 – dzim 2016-10-25 15:10:47

0

你可以只是把它Concat的使用

label.textProperty().bind(Bindings.concat(value).concat("$")); 
+0

谢谢,但是你知道如何使用NumberFormat实例吗? – Roland 2015-03-13 09:07:27

+0

我不确定NumberFormat是否可以这样做,因为numberformat具有预定义的货币前缀/后缀表达式。 – ItachiUchiha 2015-03-13 09:36:16

+0

它似乎与我发布的MoneyStringConverter一起工作。或者你看到一个问题呢?主要目标是拥有一个setValue()方法,并且所有内容都应该隐式更新,而不必使用ChangeListener或e。 G。多个updateTextField()方法。 – Roland 2015-03-13 09:54:52

0

像这样的东西应该工作的价值。现在

Bindings.format("%.2f $", myDoubleProperty.getValue()); 

如果你想使用的NumberFormat实例,只是格式化它的myDoubleProperty的值,你可以将其绑定

label.textProperty.bind(Bindings.format("%.2f $", myDoubleProperty.getValue()); 

NumberFormat formatter = NumberFormat.getInstance(); 
formatter.setSomething(); 
formatter.format(myDoubleProperty.getValue()); 

现在将其添加到我们的Bindings.format。

编辑:

包含ItachiUchiha的输入。

+1

更好地使用'label.textProperty()。bind(Bindings.format(“%。2f $”,value));',因为它是一个'DoubleProperty' – ItachiUchiha 2015-03-13 09:03:40

+0

@IchichiUchiha绝对正确。谢谢! – NDY 2015-03-13 09:06:32

+0

谢谢,但我需要使用格式化程序,而不是格式字符串。 – Roland 2015-03-13 09:06:48