Question

i have a JTable and a custom table model , wich has in some places Double.class as column class. I read from a database and then insert result to the table. I want the numbers to be rendered with 2 decimals so i use this class

    public class NumberCellRender extends DefaultTableCellRenderer {

        DecimalFormat numberFormat = new DecimalFormat("#.00");

@Override
        public Component getTableCellRendererComponent(JTable jTable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(jTable, value, isSelected, hasFocus, row, column);
            if (c instanceof JLabel && value instanceof Number) {
                JLabel label = (JLabel) c;
                label.setHorizontalAlignment(JLabel.RIGHT);
                Number num = (Number) value;
                String text = numberFormat.format(num);
                label.setText(text);

            }
            return c;

} }

The problem is when i call addRow, the Double.class columns didn't format

  public void addRowData( IEntity entity ) {
        getRowsData().add(entity);
        fireTableDataChanged();
    }

The question is when i call this i have to call something more to render the table??

Was it helpful?

Solution

For example to override the getColumnClass() method:

        public Class getColumnClass(int column)
        {
            for (int row = 0; row < getRowCount(); row++)
            {
                Object o = getValueAt(row, column);

                if (o != null)
                {
                    return o.getClass();
                }
            }

            return Object.class;
        }

Then to add the renderer to the table you do:

table.setDefaultRenderer(Double.class, new NumberCellRenderer());

You might also want to check out Table Format Renderers for some generic renderers and you could use:

table.setDefaultRenderer(Double.class, new NumberRenderer( new DecimalFormat("#.00") ));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top