JTable cell editor number format

前端 未结 4 912
耶瑟儿~
耶瑟儿~ 2020-12-06 07:31

I need to show numbers in jTable with exact 2 decimal places. To accomplish this I have created a custom cell editor as:

public class NumberCellEditor extend         


        
相关标签:
4条回答
  • 2020-12-06 07:40

    Try

    DecimalFormat numberFormat = new DecimalFormat("\\d*([\\.,\\,]\\d{0,2})?");
    
    0 讨论(0)
  • 2020-12-06 07:45

    Just change #,###,###,##0.00 with #.###.###.##0,00

    0 讨论(0)
  • 2020-12-06 08:00

    for example

    import java.text.NumberFormat;
    import java.math.RoundingMode;
    import javax.swing.table.DefaultTableCellRenderer;
    
    
    public class SubstDouble2DecimalRenderer extends DefaultTableCellRenderer {
    
        private static final long serialVersionUID = 1L;
        private int precision = 0;
        private Number numberValue;
        private NumberFormat nf;
    
        public SubstDouble2DecimalRenderer(int p_precision) {
            super();
            setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
            precision = p_precision;
            nf = NumberFormat.getNumberInstance();
            nf.setMinimumFractionDigits(p_precision);  
            nf.setMaximumFractionDigits(p_precision);
            nf.setRoundingMode(RoundingMode.HALF_UP);  
        }
    
        public SubstDouble2DecimalRenderer() {
            super();
            setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
            nf = NumberFormat.getNumberInstance();
            nf.setMinimumFractionDigits(2);
            nf.setMaximumFractionDigits(2);
            nf.setRoundingMode(RoundingMode.HALF_UP);
        }
    
        @Override
        public void setValue(Object value) {
            if ((value != null) && (value instanceof Number)) {
                numberValue = (Number) value;
                value = nf.format(numberValue.doubleValue());
            }
            super.setValue(value);
        }
    }
    
    0 讨论(0)
  • 2020-12-06 08:01

    Use the locale to your advantage:

      //Locale myLocale = Locale.GERMANY;  //... or better, the current Locale
    
      Locale myLocale = Locale.getDefault(); // better still
    
      NumberFormat numberFormatB = NumberFormat.getInstance(myLocale);
      numberFormatB.setMaximumFractionDigits(2);
      numberFormatB.setMinimumFractionDigits(2);
      numberFormatB.setMinimumIntegerDigits(1);
    
      edit.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
                        new NumberFormatter(numberFormatB)));
    
    0 讨论(0)
提交回复
热议问题