gpt4 book ai didi

java - 接受不带小数点的货币格式的 JFormattedTextField

转载 作者:行者123 更新时间:2023-12-01 17:23:01 25 4
gpt4 key购买 nike

如何编写 JFormattedTextField 代码以接受不带小数的货币格式?

我尝试到处寻找答案。具体来说,是 Oracle、Google 和 Code Ranch。

我的问题:如何对格式化文本字段进行编码以接受不带小数的货币格式。文本字段可接受 5 美元到 10,000,000 美元之间的任何值。我希望它在需要时包含“,”。该字段不会用于数学表达式,因此无需将其从字符串转换。

这是我尝试使用的代码。这种格式不允许我在格式化文本字段中输入任何数字。

buildInfo方法

//The buildInfo method will build the info panel
private void buildInfo()
{
info = new JPanel();
GridLayout gl = new GridLayout (3,1);
info.setLayout (gl);

//Create panel, label, and text area for pledgers name
p1 = new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
label1 = new JLabel ("Pledger's Name: ");
p1.add (label1);
text1 = new JTextField (20);
p1.add (text1);

//Create panel, label, and text area for pledge amount
p2 = new JPanel();
p2.setLayout(new FlowLayout(FlowLayout.LEFT));
label2 = new JLabel ("Pledged Amount: ");
p2.add (label2);
NumberFormat amount = NumberFormat.getCurrencyInstance(Locale.US);
amount.setMaximumFractionDigits(0);
NumberFormatter pAmount = new NumberFormatter(amount);
pAmount.setMinimum(5.0);
pAmount.setMaximum(10000000.0);
pAmount.setAllowsInvalid(false);
text2 = new JFormattedTextField (pAmount);
text2.setColumns(12);
p2.add (text2);

//Create panel, label, and text area for charity being pledged
p3 = new JPanel();
p3.setLayout(new FlowLayout(FlowLayout.LEFT));
label3 = new JLabel ("Charity Pledged To:");
p3.add (label3);
text3 = new JTextField (20);
p3.add (text3);

//Add panels to main panel
add(p1);
add(p2);
add(p3);
}

最佳答案

使用

NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
format.setMaximumFractionDigits(0);

NumberFormatter formatter = new NumberFormatter(format);
formatter.setMinimum(5.0);
formatter.setMaximum(10000000.0);
formatter.setAllowsInvalid(false);
formatter.setOverwriteMode(true);

JFormattedTextField field = new JFormattedTextField(formatter);
field.setValue(5.0);

关于java - 接受不带小数点的货币格式的 JFormattedTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17246676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com