Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using intercellSpacing in a JTable with a custom row background color causes unexpected results

I have a JTable where I want to highlight some rows using a custom background-color. This I have done with the following class:

public class MyTable extends JTable {

    private List<RefData> data = null;

    public List<RefData> getData() {
        return data;
    }

    public void setData(List<RefData> data) {
        this.data = data;
    }

    @Override
    public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
        Component comp = super.prepareRenderer(renderer, row, column);

        if (this.data == null || row < 0 || row > this.data.size()-1){
            return comp;
        }

        RefData rowData = this.data.get(row);
        if (rowData.getStatus() < 3000){
            comp.setBackground(Color.YELLOW);
        } else {
            comp.setBackground(Color.WHITE);
        }

        return comp;
    }

}

All this works like a charm, and I get exactly what I want. Next, while looking at the resulting GUI, I realise that the table looks way too condensed. Everything looks squished together. As always with the default JTable settings ;)

Well, that's easily solved I thought:

myTable.setIntercellSpacing(new java.awt.Dimension(10, 1));

Now, the cells are nicely spaced but, the added cell margins are now in the default table background color, which in my case is white. This looks butt-ugly.

I assume that the intercell spacing adds spacing between the cell border and the component returned by prepareRenderer. This would explain the result. But how can I get it to change the background of the cell itself?

Is my prepareRenderer solution is not suited for this task? Or is there another solution?

like image 844
exhuma Avatar asked Feb 25 '23 21:02

exhuma


1 Answers

The Border approach is correct, but it is better to do it the cell renderer, not the prepareRenderer() method:

    JTable.setDefaultRenderer(Object.class, new DefaultCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            JComponent component = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            component.setBorder(...);
            return component;
        }
    });
like image 196
Denis Tulskiy Avatar answered Feb 28 '23 09:02

Denis Tulskiy