【问题标题】:How to format text of TextField? JavaFX如何格式化TextField的文本? JavaFX
【发布时间】:2015-07-13 11:32:33
【问题描述】:

例如,如果我输入 32164578542324236.97325074,则该数字应显示在 TextField 中,例如 32,164,578,542,324,236.97325074。 我试图处理这个问题,但没有成功:

    inputField.textProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            BigDecimal bd = new BigDecimal(newValue);
            NumberFormat formatter = NumberFormat.getNumberInstance();             
            inputField.setText(formatter.format(newValue));
        }
    });

也许使用 inputField.setTextFormatter(); 会更好。但我不熟悉这种方法。 提前致谢!

【问题讨论】:

  • 请在询问前使用本站的“搜索”。见this
  • 我看到了那个页面,但是通过那个例子很难理解这个方法是如何工作的。
  • 基本上你需要在那个例子中配置 DecimalFormat 的模式。请花一些时间通过阅读其 javadoc 来了解 DecimalFormat 模式和其他配置(如千位分隔符),如果这也很难,请在网上搜索更详细的示例代码教程。

标签: java text javafx formatting textfield


【解决方案1】:

试试:

BigDecimal bd = new BigDecimal(newValue);
DecimalFormat formatter  = new DecimalFormat(",###");// seperate them by ',' while digits after '.' are excluded
String newestValue = formatter.format(bd)+newValue.substring(newValue.indexOf("."));// concatenate with the digits after '.'
inputField.setText(newestValue);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2021-10-17
    • 2014-11-15
    • 2014-09-02
    • 2018-07-18
    • 2015-09-30
    • 1970-01-01
    相关资源
    最近更新 更多