Java 使用JFormattedTextField(NumberFormat.getIntegerInstance())时出错;

Java 使用JFormattedTextField(NumberFormat.getIntegerInstance())时出错;,java,swing,Java,Swing,我尝试使用时遇到问题: JFormattedTextField(NumberFormat.getIntegerInstance()); 当我将一个数字放入数字框时,我得到一个错误,即我输入的数字是错误的,因为数字之间有空格,如:200000,当数字是200000时,我没有错误。您可以使用中所述的MaskFormatter,以避免获取非数字字符: JFormattedTextField textField = new JFormattedTextField(new MaskFormatt

我尝试使用时遇到问题:

JFormattedTextField(NumberFormat.getIntegerInstance());

当我将一个数字放入数字框时,我得到一个错误,即我输入的数字是错误的,因为数字之间有空格,如:
200000
,当数字是
200000
时,我没有错误。

您可以使用中所述的
MaskFormatter
,以避免获取非数字字符:

    JFormattedTextField textField = new JFormattedTextField(new MaskFormatter("#######"));
但是,如果使用这种方式,在复制粘贴文本
200000
时,将不会粘贴该文本,或者只粘贴200。(空格后的剩余部分-将忽略非数字字符)

为了实现这一点,您必须使用仅保留数字的。因此,当输入带有空格
200000
时,它将保持
200000

class NumberOnlyDocumentFilter extends DocumentFilter {
    @Override
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
            throws BadLocationException {
        super.insertString(fb, offset, keepOnlyDigits(string), attr);
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
            throws BadLocationException {
        super.replace(fb, offset, length, keepOnlyDigits(text), attrs);
    }

    private String keepOnlyDigits(String text) {
        StringBuilder sb = new StringBuilder();
        for (char c : text.toCharArray())
            if (Character.isDigit(c))
                sb.append(c);
        return sb.toString();
    }
}
以及“安装”它:

JTextField textField = new JTextField();
AbstractDocument document = (AbstractDocument) textField.getDocument();
document.setDocumentFilter(new NumberOnlyDocumentFilter());