2015-03-13 55 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