【问题标题】:Format price textfield real time in javaFX在javaFX中实时格式化价格文本字段
【发布时间】:2020-05-02 11:14:27
【问题描述】:

当用户实时输入数字时,我想在文本字段中格式化价格,例如 100,000,000。 有没有办法做到这一点?

【问题讨论】:

标签: java javafx format textfield text-formatting


【解决方案1】:

您可以轻松地尝试使用十进制格式化程序:

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>

【讨论】:

  • 这是答案的一部分 - 另一部分是在用户输入时强制执行格式:)
【解决方案2】:

这是一个简单的解决方案:

       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);
                }
            }

        });

【讨论】:

  • 不,使用属性监听器并在收到通知时更改其值是根本错误!请改用 TextFormatter,该类专为您的用例而设计
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-04
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多