Search code examples
javaswingjtabletablecellrenderer

Change JTable cell colours without clicking


In a nutshell, I've got a JTable populated with hex data. The table remains on screen whilst some background processing occurs.

The background processing checks some 8 byte values, and if for example, the first 8 bytes are processed successfully, I need the first 8 cells in the table to change their background colour to green. This goes on for the next 8, until the end of the table.

But I can't figure out how to achieve this.

public class MyCellRenderer extends javax.swing.table.DefaultTableCellRenderer {

    @Override
    public java.awt.Component getTableCellRendererComponent(javax.swing.JTable table, java.lang.Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        java.awt.Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        System.out.println("Cell render test");
        cellComponent.setBackground(java.awt.Color.GREEN);
        return cellComponent;
    }
}

This is some code I've found that allows for the rendering of a cell, however it only seems to apply for entire columns, using the:

.getColumnModel().getColumn(10).setCellRenderer(customRenderer);

I guess there are two distinct problems here:

  1. How to specify an exact range of cells to apply a custom render to, i.e. row 0, columns 0-7?
  2. How to apply this without the user interacting with the table. A lot of the custom rendering stuff I can find is for when a user selects a cell, but in this instance, no cells are being manually selected. I'm guessing it might be a case of triggering some kind of event.

If anyone can offer any advice or input, I'd greatly appreciate it.


Solution

  • The last arguments to the method are row and column. To get the required result, the renderer must take those values into account.