Using intercellSpacing in JTable with custom background color causes unexpected results

I have a JTable where I want to highlight some lines using my own background color. I did this 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;
    }

}

It all works like a charm, and I get exactly what I want. Then, looking at the resulting graphical interface, I understand that the table looks too compressed. Everything looks bad. As always with JTable defaults;)

Well, this is easy to solve, I thought:

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

Now the cells are well spaced , but the added cell fields are now in the background color of the table by default, which in my case is white. It looks indecent.

, , prepareRenderer. . ?

prepareRenderer ? ?

+3
3

. . -, , , ( ) , ?

public class MyTable extends JTable {

    // [snip]

    private Border paddingBorder = BorderFactory.createEmptyBorder(2, 3, 2, 3);

    // [snip]

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

        if (JComponent.class.isInstance(comp)){
            ((JComponent)comp).setBorder(paddingBorder);
        }

        // [snip]
    }

    // [snip]

}
+1

Border , , prepareRenderer():

    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;
        }
    });
+3

-, , , Swing, ?

Overriding prepareRenderer()has the advantage of applying to all cells, and "internal implementations always use this method to prepare renderings so that this default behavior can be safely overridden by a subclass." I do not see a problem, even if you later use setDefaultRenderer()for a specific class.

Appendix: examples can be found in the article Table Row Rendering , and this related answer .

+3
source

Source: https://habr.com/ru/post/1773588/