1

I would like to change the color of a cell in a JTable. I wrote my own class that extends DefaultTableCellRenderer. However, my class has really inconsitent behavior. All it does is if a entry appears twice in a column, it marks it red. This is the result I get:

enter image description here

Notice that in this class I am also setting the font for a particular column. That works fine. I am wondering why I get this behavior when trying to simply set the color.

Here is my class:


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package inter2;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

/**
 * Used to display different fonts for different cells in the table
 */
public class CustomCellRenderer extends DefaultTableCellRenderer
{

    private final int TRANSLATION_COL = 1;
    private final int VARIABLE_COL = 2;

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int column)
    {
        Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        //set it so it can display unicode characters
        if (column == TRANSLATION_COL)
        {
            cell.setFont(new Font("MS Mincho",Font.PLAIN, 12));
        }
        //marks a cell red if it is a duplicate variable name
        if(column == VARIABLE_COL)
        {
            MyTable theTable = (MyTable)table;
            String cellValue = theTable.getValueforCell(row, column);
            boolean dup = false;
            String[] columnData = theTable.getColumnData(column);
            //check if this is already in the list
            for(int i =0; i &lt columnData.length; i++)
            {
                String currTableValue = columnData[i];
                if(currTableValue.equals(cellValue) && i != row)
                {
                    dup = true;
                    break;
                }
            }
            //we found a dup
            if(dup == true)
            {
                cell.setBackground(Color.red);
            }
        }
        return cell;
    }
}

user663321
  • 1,963
  • 2
  • 14
  • 10

1 Answers1

4

DefaultTableCellRenderer is a particularly bad implementation - you hit it's infamous "color memory". To work around, you have to set its color properties always

if (myCondition) 
    comp.setBackground(red)
else 
    comp.setBackground(normal)

or better (biased me, of course): use JXTable in SwingX, it comes with full pluggable support for decorating cell renderers, not only in a table, but consistently in comboBox, tree, list ..

kleopatra
  • 51,061
  • 28
  • 99
  • 211