本文介绍了如何格式化TextField的文本? JavaFX的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For example, if I enter 32164578542324236.97325074, this number should be displayed in a TextField like 32,164,578,542,324,236.97325074.I tried to handle this, but unsuccessfully:

    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()可能会更好;但我不熟悉这种方法。
提前致谢!

Maybe it would be better to use inputField.setTextFormatter(); but I'm not familiar with this method.Thanks in advance!

推荐答案

尝试:

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

这篇关于如何格式化TextField的文本? JavaFX的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:03