0

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?

user1761818
  • 365
  • 1
  • 7
  • 14
  • 1
    Talk more about write way. Is this a read way for me? – Roman C Nov 07 '12 at 11:10
  • 1
    @AndrewThompson, you edited and let "write way" stay there!? – HericDenis Nov 07 '12 at 11:12
  • @user1761818, you should put here what you tried. – HericDenis Nov 07 '12 at 11:14
  • @HericDenis 1) I did not edit (or carefully read) the body, just the tags. 2) When I do, it is mostly the 'red squiggly underlines' that FF thinks are wrongly spelled, that draws my eye to them. So even if I had edited the body, it is unlikely I would have noticed the difference between 'write' and 'right'. ;) – Andrew Thompson Nov 07 '12 at 11:15
  • 1
    Have a look at [How to Use Tables](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html) in particular [Using an Editor to Validate User-Entered Text](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#validtext) – MadProgrammer Nov 07 '12 at 11:15
  • That's ok @AndrewThompson, I was just annoying you bro (: – HericDenis Nov 07 '12 at 12:08

1 Answers1

4
  • 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);
        }
    }
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319