2016-05-27 151 views
0

我有一個TextField,其中用戶輸入工資。 TF有一個基於默認語言環境的TextFormatter。旁邊的文本字段有一個標籤,在該標籤我想顯示爲貨幣格式的文本字段的文本,對於這一切我用這個代碼:javafx:使用TextField的+ FORMAT結果綁定標籤文本屬性

TextField text = new TextField(); 
Label show = new Label(); 

TextFormatter<Number> formatter = new TextFormatter<>(new FormatStringConverter<>(DecimalFormat.getNumberInstance())); 

text.setTextFormatter(formatter); 

show.textProperty().bind(Bindings.concat(text.getTextFormatter().valueProperty().asString()) 
.concat(" ").concat(Currency.getInstance(Locale.getDefault()).getCurrencyCode())); 

return new HBox(text, show); 

結果: enter image description here

正如你可以看到標籤文本沒有格式化爲數字 - 因爲沒有應用格式化程序。 所以我的問題是如何使標籤的文本格式化並使用TextField TextProperty綁定相同時間。

可能有人會問:爲什麼不使用的,而不是數字格式化貨幣格式,如:

new TextFormatter<>(new FormatStringConverter<>(DecimalFormat.getCurrencyInstance())); 

很好的答案是,當用戶想要輸入的值,他將需要刪除所有的數字,但例如美元符號,如果用戶輸入一個沒有美元符號的值,新值將不被接受。

這就是爲什麼我要顯示格式化值作爲標籤中的貨幣,而不是使用貨幣格式化程序。謝謝。

回答

0

這裏是我曾經

text.focusedProperty().addListener((ObservableValue<? extends Boolean> arg0, Boolean oldPropertyValue, Boolean newPropertyValue) -> { 
     if(!newPropertyValue){ 
      show.setText(form.format(formatter.getValue().doubleValue())); 
     } 
    }); 
解決方案
0

這是不完全相同的格式,但可能是你需要的。

NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); 
    show.textProperty().bind(Bindings.createStringBinding(
     () -> formatter.getValue() == null 
       ? "" 
       : currencyFormat.format(formatter.getValue().doubleValue()),   
     formatter.valueProperty()));