我用一个 NumberFormatterJFormattedTextField, 但 .getValue() 不返回值相同的用户看到。

我觉得输入串的是分析使用NumberFormats分析方法,并且我得到的数字格式从 NumberFormat.getNumberInstance(); 实际区域设置。所以我不认为我可以很容易地扩展它,并写入我自己的分析方法?

, 如果用户的类型 1234.487getValue() 将返回:1234.487 但是,用户将会显示 1,234.49

另一个例子, 使用 NumberFormat.getCurrencyInstance();.用户的类型 1234.487getValue() 将返回 1234.487 但是,用户将会显示 $1,234.49

而不是, 我想如果可以生成果的格式不能格式化价值而进行四舍五入的处理。同样的事情,如果用户的类型 4.35b6, 通过默认器会显示 4.35 和价值将 4.35, 但是我想如果,因为用户类型中的一个 无效 值。

这里是代码,我已经试过:

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
final JFormattedTextField ftf = new JFormattedTextField(nf);
ftf.setValue(new BigDecimal("1234.50"));

// Print the value from ftf
final JTextField txt = new JTextField(12);
txt.addFocusListener(new FocusAdapter() {
    public void focusGained(FocusEvent e) {
        txt.setText(ftf.getValue().toString());
    }
});

如何获得同等价值的用户看到?

有帮助吗?

解决方案

你应该延伸 NumberFormatter 而不是 NumberFormat 和复盖 stringToValue 因此,它将验证当串的是解析的,你得到回原来的价值:

class StrictNumberFormatter extends javax.swing.text.NumberFormatter {
    @Override
    public Object stringToValue(String text) throws ParseException {
        Object parsedValue = super.stringToValue(text);
        String expectedText = super.valueToString(parsedValue);
        if (! super.stringToValue(expectedText).equals(parsedValue)) {
            throw new ParseException("Rounding occurred", 0);
        }
        return parsedValue;
    }

    public StrictNumberFormatter(NumberFormat nf) {
        super(nf);
    }
}

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
JFormattedTextField.AbstractFormatter formatter = new StrictNumberFormatter(nf);
final JFormattedTextField ftf = new JFormattedTextField(formatter);
ftf.setValue(new BigDecimal("1234.50"));

这一格式将拒绝新的文本,如果价值之前和之后的四舍五入的不匹配。

注:这个比较 , 不串。它将容忍的变化删除分组的字符的("$1,000" => "$1000")和后为零("$1.20" => "$1.2").基本上如果 NumberFormat 返回相同的价值,那么它是可以接受的。但是,任何施加的限制 NumberFormat 仍然适用,例如不,你必须去除货币符号或插入领先的空间等。

其他提示

试试这个:

txt.setText(ftf.getFormatter().valueToString(ftf.getValue()));

你也有要处理的 java.text.ParseException 这的 valueToString 方法抛出。

编辑: 格式可以是设置不允许完全无效的项目,这可能会有所帮助:

    ((DefaultFormatter)ftf.getFormatter()).setAllowsInvalid( false );
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top