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?
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With