2015-07-13 120 views
1

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

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();但我不熟悉这种方法。 在此先感谢!

+0

请使用本网站的前问 “搜索”。看到[this](http://stackoverflow.com/a/31043122) –

+0

我看到了那个页面,但很难理解这个方法在这个例子中是如何工作的。 – void

+0

基本上你需要在那个例子中配置DecimalFormat的模式。请花一些时间通过阅读它的javadoc来了解DecimalFormat模式和其他配置(如千位分隔符),如果这也很难,请使用示例代码在网络中搜索更详细的教程。 –

回答

0

尝试:

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