JTable row background color not changing for Double or Integer

892 views Asked by At

I am changing the background color of a row in JTable using following code. The color of row gets changed for all the cells which have String values however it does not gets changed for cells with Integer or Double values.

  private JTable getNewRenderedTable(final JTable table) {
        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
                Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
                String status = (String)table.getModel().getValueAt(row, index);
                if (Constants.seller.equals(status)) {
                    c.setBackground(Color.GRAY);
                    //setForeground(Color.WHITE);
                } else {
                    c.setBackground(table.getBackground());
                    c.setForeground(table.getForeground());
                }       
                return c;
            }   
        });
        return table;
    }
1

There are 1 answers

1
Sergiy Medvynskyy On BEST ANSWER

Try to register the same renderer also for Integer and Double. These classes have separate default renderer registered by default. Something like this.

private JTable getNewRenderedTable(final JTable table) {
    table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
            String status = (String)table.getModel().getValueAt(row, index);
            if (Constants.seller.equals(status)) {
                c.setBackground(Color.GRAY);
                //setForeground(Color.WHITE);
            } else {
                c.setBackground(table.getBackground());
                c.setForeground(table.getForeground());
            }       
            return c;
        }   
    });
    table.setDefaultRenderer(Number.class, table.getDefaultRenderer(Object.class));
    table.setDefaultRenderer(Double.class, table.getDefaultRenderer(Object.class));
    return table;
}