user1761818
user1761818

Reputation: 375

how to use DefaultCellEditor to make column of the JTable to get only numbers and round them with two signs after dot?

I am not sure if this is the right way to do this but I think so. I have tried to use DecimalFormat but I cant understand it. Can someone help me? Is this the correct way to do this DefaultCellEditor + DecimalFormat?

Upvotes: 0

Views: 1673

Answers (1)

mKorbel
mKorbel

Reputation: 109813

  • override column class by using Double.Class

  • for XxxTableCellEditor to use JFormattedTextField or JSpinner as Editor, formatted by proper methods from NumberFormat or DecimalNumberFormat, including rounding

  • set DefaultTableCellRenderer for desired colum

  • you can to set (too) proper Rounding method from NumberFormat

for example

TableColumnModel tcmAmount = myTable.getColumnModel();    
TableColumn tcAmount = tcmAmount.getColumn(2);
tcAmount.setCellRenderer(new DRManMmAmount(1)); // decimal precision

and

   private static class DRManMmAmount extends DefaultTableCellRenderer {

        private static final long serialVersionUID = 1L;
        int precision = 0;
        Number numberValue;
        NumberFormat nf;

        public DRManMmAmount(int p_precision) {
            super();
            setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
            precision = p_precision;
            nf = NumberFormat.getNumberInstance();
            nf.setMinimumFractionDigits(p_precision);
            nf.setMaximumFractionDigits(p_precision);
            //nf.setMinimumFractionDigits(2);
            //nf.setMaximumFractionDigits(2);
        }

        @Override
        public void setValue(Object value) {
            if ((value != null) && (value instanceof Number)) {
                numberValue = (Number) value;
                value = nf.format(numberValue.doubleValue()); 
            }
            super.setValue(value);
        }
    }

Upvotes: 4

Related Questions