如何在表中存储舍入值而不是仅将其显示为舍入值

时间:2014-06-05 13:38:06

标签: java jtable tablecellrenderer tablecelleditor

我有一张表格,我需要将数字四舍五入到小数点后4位。我已设法做到这一点,但问题是,当表显示舍入值时,存储的实际值不是舍入值(我使用BigDecimal,因为我希望能够控制单元格的舍入行为)。当我打印单元格值时,我得到的数字超过4个十进制值,即使表中显示的值是舍入值。我写了自己的编辑和渲染器如下:

class DoubleEditor4 extends DefaultCellEditor {

    public DoubleEditor4() {
        super(new JFormattedTextField());
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        JFormattedTextField editor = (JFormattedTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);
        if (value!=null){
            String num = (String) value;
            BigDecimal num2 = new BigDecimal(num).setScale(4, BigDecimal.ROUND_HALF_UP);
            String text = num2.toString();
            editor.setHorizontalAlignment(SwingConstants.RIGHT);
            editor.setText(text);
        }
        return editor;
    }   
}

class DoubleRenderer4 extends DefaultTableCellRenderer {
    public DoubleRenderer4() { 
        super();
        this.setHorizontalAlignment(SwingConstants.RIGHT);
    }

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        value = new BigDecimal(value.toString()).setScale(4, BigDecimal.ROUND_HALF_UP);
        return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column );
    }

    public void setValue(Object value) {
        BigDecimal num2 = new BigDecimal(value.toString()).setScale(4, BigDecimal.ROUND_HALF_UP);
        String text = num2.toString();
        setText(text);
    }
}

我做错了什么,表格模型中存储的值不是舍入值?感谢。

1 个答案:

答案 0 :(得分:0)

我设法通过覆盖单元格编辑器类中的getCellEditorValue()方法来解决问题:

@Override
public Object getCellEditorValue() {
    Object v = super.getCellEditorValue();
    BigDecimal n = new BigDecimal(v.toString()).setScale(4, BigDecimal.ROUND_HALF_UP);
    return n.toString();
}