My columns in the JTable don't get all a background color

34 views Asked by At

My columns in my table don't all get a background color. If I use a checkbox in my table, it does not get a background color.

I used this code to set the background:

participantsTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(row % 2 == 0 ? new Color(230, 230, 230): Color.WHITE);
        return this;
    }
});

I've tried searching the internet for a solution, but to no avail. I'm not so familiar with the JTabel that I could come up with the error myself.

Here is what shouldn't happen: Here is what shouldn't happen

So it shouldn't look like that, but the background of the checkbox should be the same as the column to the left of it.

What am I doing wrong and how can I fix this problem?

1

There are 1 answers

0
camickr On

the background of the checkbox should be the same as the column to the left of it.

Different data types use different renderers.

In your case you would also need to customize the renderer for the Boolean.class.

Or alternatively you can override the prepareRenderer(...) method of the JTable.

A basic example would be:

JTable table = new JTable( model )
{
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
    {
        Component c = super.prepareRenderer(renderer, row, column);

        //  Alternate row color

        if (!isRowSelected(row))
            c.setBackground(row % 2 == 0 ? getBackground() : Color.LIGHT_GRAY);

        return c;
    }
};

This method is invoked after the renderer for the cell has been determined so it will work for all columns of the table.

Check out Table Row Rendering for more information and examples of custom rendering using this approach.