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

时间:2013-06-22 02:11:46

标签: java swing jformattedtextfield currency-formatting

如何编码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);
}

1 个答案:

答案 0 :(得分: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);