英文:
Format price textfield real time in javaFX
问题
我想在用户实时输入数字时,将价格格式设置为文本字段中的样式,如 100,000,000。有没有办法做到这一点?
英文:
I want to format the price like 100,000,000 in textfield while users are entering number in it real time.
Is there any way to do that?
答案1
得分: 0
你可以轻松尝试使用十进制格式化程序:
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());
}
}
希望这是你所寻找的内容。
英文:
You can easily try with a decimal formatter:
DecimalFormat myFormat = new DecimalFormat("###,##0.00");
myFormat.format(yourValue);
If you want the decimal digits only if presents use the pattern "###,###.##"
.
EDIT
If you want to update while the user is typing, you should use the onAction
methods of JavaFX.
For example you could do:
If this is your TextField (you can have it even in a controller)
<TextField fx:id="money" onKeyTyped="#updateText">
</TextField>
Controller
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());
}
}
Hope it was what you were looking for.
答案2
得分: -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);
}
}
});
英文:
Here is a simple solution:
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);
}
}
});
专注分享java语言的经验与见解,让所有开发者获益!
评论