【发布时间】:2020-05-02 11:14:27
【问题描述】:
当用户实时输入数字时,我想在文本字段中格式化价格,例如 100,000,000。 有没有办法做到这一点?
【问题讨论】:
-
搜索 TextFormatter - 你需要实现一个自定义过滤器
标签: java javafx format textfield text-formatting
当用户实时输入数字时,我想在文本字段中格式化价格,例如 100,000,000。 有没有办法做到这一点?
【问题讨论】:
标签: java javafx format textfield text-formatting
您可以轻松地尝试使用十进制格式化程序:
DecimalFormat myFormat = new DecimalFormat("###,##0.00");
myFormat.format(yourValue);
如果您只需要十进制数字,请使用模式"###,###.##"。
编辑
如果您想在用户输入时更新,您应该使用 JavaFX 的 onAction 方法。
例如你可以这样做:
如果这是你的 TextField(你甚至可以在控制器中拥有它)
<TextField fx:id="money" onKeyTyped="#updateText">
</TextField>
控制器
public class Controller {
@FXML
private TextField money;
DecimalFormat myFormat = new DecimalFormat("###,##0.00");
@FXML
public void updateText(){
this.money.setText(myFormat.format(Double.valueOf(money.getText())).toString());
}
}
希望这是您要找的。p>
【讨论】:
这是一个简单的解决方案:
priceField.textProperty().addListener((observable, oldValue, newValue) -> {
if (!priceField.getText().equals("")) {
DecimalFormat formatter = new DecimalFormat("###,###,###,###");
if (newValue.matches("\\d*")) {
String newValueStr = formatter.format(Long.parseLong(newValue));
priceField.setText(newValueStr);
} else {
newValue = newValue.replaceAll(",", "");
String newValueStr = formatter.format(Long.parseLong(newValue));
priceField.setText(newValueStr);
}
}
});
【讨论】: