0

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

我试着到处寻找我的答案。在这里,甲骨文、谷歌和 Code Ranch 是具体的。

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

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

构建信息方法

//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);
}
4

1 回答 1

5

利用

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);
于 2013-06-22T02:23:19.540 回答