如何使JFormattedTextField使用$ 1.55,但将值存储为Integer 155?

时间:2011-11-19 09:14:43

标签: java swing number-formatting jformattedtextfield

几乎所有我读过的关于Java的内容都说不要使用float或double作为货币,但是如果你想输入/显示有十进制的货币值,似乎Swing中的所有内容都试图强制你这么做地方(也就是大多数人想要做的事情)。

我可以将NumberFormat.getCurrencyInstance()NumberFormatterJFormattedTextField一起使用,但我无法弄清楚如何在不使用Float或{{{{}}的情况下显示小数位数1}}。我必须忽略一些简单的事情。

如何让我的货币字段显示为Double,接受输入为$1.55并将输入存储为值为1.55(美分)的整数?

2 个答案:

答案 0 :(得分:2)

你无法对格式化程序进行数学运算。你应该做的是你的pojo的成员变量以美分为单位。类似的东西:

private long priceInDollarCents;

然后你可以得到一个将以美元回报的吸气剂。类似的东西:

public double getPriceInDollars() {
    return (double)priceInDollarCents/100;
}

这是您将传递给格式化程序的内容。

答案 1 :(得分:1)

您可以这样做:

enter image description here

<强> CustomizedField.java

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class CustomizedField extends JTextField
{
    private static final long serialVersionUID = 1L;

    public CustomizedField(int size)
    {
        super(size);
        setupFilter();
    }

    public int getCents()
    {
        String s = getText();
        System.out.println(s);
        if(s.endsWith(".")) s = s.substring(0, s.length() - 1);
        double d = Double.parseDouble(s) * 100;
        return (int) d;
    }

    private void setupFilter()
    {

        ((AbstractDocument) getDocument()).setDocumentFilter(new DocumentFilter()
        {

            @Override
            public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
            {
                check(fb, offset, text, attr);
            }

            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
            {
                check(fb, offset, text, attr);
            }

            private void check(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
            {
                StringBuilder sb = new StringBuilder();
                sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
                sb.insert(offset, text);
                if(!containsOnlyNumbers(sb.toString())) return;
                fb.insertString(offset, text, attr);
            }

            private boolean containsOnlyNumbers(String text)
            {
                Pattern pattern = Pattern.compile("([+-]{0,1})?[\\d]*.([\\d]{0,2})?");
                Matcher matcher = pattern.matcher(text);
                boolean isMatch = matcher.matches();
                return isMatch;
            }

        });
    }

}

<强> Test.java

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Test
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Testing CustomizedField");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());

        final CustomizedField cField = new CustomizedField(10);
        final JTextField output = new JTextField(10);
        JButton btn = new JButton("Print cents!");
        btn.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent event)
            {
                output.setText(cField.getCents() + " cents");
            }
        });

        frame.add(cField);
        frame.add(btn);
        frame.add(output);
        frame.pack();
        frame.setVisible(true);
    }
}