Question

I have a table in which I need the numbers to be rounded to 4 decimal places. I have managed to do that but the problem is that while the table is displaying the rounded values, the actual values stored are not the rounded values (I use BigDecimal because I want to be able to control the rounding behaviour of the cells). When I print the cell values I get the numbers with more than 4 decimal values even though the values showed in the table are the rounded values. I wrote my own editors and renderers as follows:

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);
    }
}

What am I doing wrong such that the stored values in the table model are not the rounded values? Thanks.

Was it helpful?

Solution

I managed to solve the problem by overriding the getCellEditorValue() method in the cell editor class as such:

@Override
public Object getCellEditorValue() {
    Object v = super.getCellEditorValue();
    BigDecimal n = new BigDecimal(v.toString()).setScale(4, BigDecimal.ROUND_HALF_UP);
    return n.toString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top