【问题标题】:JavaFx TextField Currency format filterJavaFx TextField 货币格式过滤器
【发布时间】:2018-07-18 15:08:32
【问题描述】:

我确实从用户那里得到了价格,但我想过滤数字并放置,每 3 位数字,如 123,123,123。

txtPrice.textProperty().addListener((observable, oldValue, newValue) -> {
   if (!newValue.matches("\\d*")){
       txtPrice.setText(newValue.replaceAll("[^\\d]",""));
   }
});

【问题讨论】:

标签: java javafx textfield


【解决方案1】:

要按照您指定的格式设置数字,您可以试试这个:

// Eg: format "123123123" as "123,123,123"
if (newValue.matches("\\d*")) {
    DecimalFormat formatter = new DecimalFormat("#,###");
    String newValueStr = formatter.format(Double.parseDouble(newValue));

    txtPrice.setText(newValueStr);
}

希望对您有所帮助,祝您好运!

【讨论】:

  • 最好使用格式来完成这项工作,更好的是在 fx TextFormatter 中使用它:)
【解决方案2】:

试试这个:

textFieldUsername.setOnKeyTyped(event -> {
    String typedCharacter = event.getCharacter();
    event.consume();

    if (typedCharacter.matches("\\d*")) {
        String currentText = textFieldUsername.getText().replaceAll("\\.", "").replace(",", "");
        long longVal = Long.parseLong(currentText.concat(typedCharacter));
        textFieldUsername.setText(new DecimalFormat("#,##0").format(longVal));
    }
});

【讨论】:

  • 不,不要在密钥处理程序中进行格式化(会错过复制或更新的文本),也不要进行任何手动格式化(会在不同的语言环境中出现)
  • 这种方法效果很好,但我们能做得更好吗?我确实搜索过TextFormatter,但我无法理解它我需要自己学习如何做到这一点,所以伙计们我应该学习什么并给我一些好的资源
猜你喜欢
  • 2022-11-09
  • 1970-01-01
  • 2013-09-15
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
相关资源
最近更新 更多