在javaFX中实时格式化价格文本字段
我想在用户实时输入数字时,在文本字段中设置100000000这样的价格。在javaFX中实时格式化价格文本字段,java,javafx,format,textfield,text-formatting,Java,Javafx,Format,Textfield,Text Formatting,我想在用户实时输入数字时,在文本字段中设置100000000这样的价格。 有办法吗 您可以轻松尝试使用十进制格式化程序: DecimalFormat myFormat = new DecimalFormat("###,##0.00"); myFormat.format(yourValue); 如果您仅在礼物使用图案时才需要十进制数字 编辑 如果希望在用户键入时进行更新,则应使用JavaFX的onAction方法 例如,您可以执行以下操作: 如果这是您的文本字段,您甚至可以在控制器中使用它 &l
有办法吗 您可以轻松尝试使用十进制格式化程序:
DecimalFormat myFormat = new DecimalFormat("###,##0.00");
myFormat.format(yourValue);
如果您仅在礼物使用图案时才需要十进制数字
编辑
如果希望在用户键入时进行更新,则应使用JavaFX的onAction方法
例如,您可以执行以下操作:
如果这是您的文本字段,您甚至可以在控制器中使用它
<TextField fx:id="money" onKeyTyped="#updateText">
</TextField>
希望这就是您想要的。这里有一个简单的解决方案:
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-您需要实现一个自定义过滤器,这是答案的一部分-另一部分是在用户键入时强制执行格式:否,使用侦听器访问属性并在收到通知时更改其值是根本错误的!请使用TextFormatter,该类正是为您的用例而设计的
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);
}
}
});