0

I've been trying to color a complete JTable row with a custom TableCellRenderer but for some reason it's only coloring my first and last cell.

I want to color based on the second and fourth value, in this case: 5 and 10. If the second value is less then the fourth, color it red. If it's equal color it yellow.

As you can see below it works out fine, but for some reason it only colors the first and last cell and I've been banging my head against the wall trying to get this to work.

Only the first and last cell are colored of the row

I assume I'm doing something wrong in my overriden getTableCellRendererComponent:

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);

    Integer minStock = (Integer) table.getModel().getValueAt(row, 3);
    Integer currentStock = (Integer) table.getModel().getValueAt(row, 1);

    if (Objects.equals(minStock, currentStock)) {
        setBackground(Color.YELLOW);
    } else if (minStock > currentStock) {
        setBackground(Color.RED);
    } else {
        setBackground(table.getBackground());
        setForeground(table.getForeground());
    }

    return this;
}

If anyone could enlighten me on how to solve this it would be greatly appreciated!

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
SliceOfLife
  • 89
  • 2
  • 7
  • Do you ever set the renderer component to being opaque? – Hovercraft Full Of Eels Jan 16 '16 at 15:56
  • 1
    If you don't get help soon, consider creating and posting a [Minimal, Complete, and Verifiable Example Program](http://stackoverflow.com/help/mcve) where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem. – Hovercraft Full Of Eels Jan 16 '16 at 15:58
  • @HovercraftFullOfEels Yes, I forgot to mention that I tried that shortly after posting this question. I call this.setOpaque(true); right after the super call. It doesn't make a difference. – SliceOfLife Jan 16 '16 at 16:15
  • 2
    Have a look at [camickr's link](http://tips4java.wordpress.com/2010/01/24/table-row-rendering/) to see if that might help you. – Hovercraft Full Of Eels Jan 16 '16 at 16:24
  • 2
    for coloring row is there the prepareRenderer – mKorbel Jan 16 '16 at 16:25
  • Where is the code showing how you add the custom renderer? Do you add it to **all** the columns? – JB Nizet Jan 16 '16 at 17:27
  • 1
    A solution is shown here: http://stackoverflow.com/questions/9735007/how-to-set-color-to-a-certain-row-if-certain-conditions-are-met-using-java – Thomas Kläger Jan 16 '16 at 17:48

0 Answers0