简体   繁体   中英

JTable row background color not changing for Double or Integer

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;
    }

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM