改变JTable中单元格的颜色

时间:2011-04-28 16:13:48

标签: java swing jtable

我想改变JTable中单元格的颜色。我编写了自己的类,扩展了DefaultTableCellRenderer。但是,我的班级确实有不一致的行为。它所做的只是一个条目在一列中出现两次,它标记为红色。这是我得到的结果:

enter image description here

请注意,在此类中,我还设置了特定列的字体。这很好。我想知道为什么在尝试简单设置颜色时会出现这种情况。

这是我的班级:


/*
 * 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 < 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;
    }
}

1 个答案:

答案 0 :(得分:4)

DefaultTableCellRenderer是一个特别糟糕的实现 - 你点击它臭名昭着的“彩色记忆”。要解决此问题,您必须设置其颜色属性始终

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

或更好(当然有偏见):在SwingX中使用JXTable,它提供完全可插拔的支持,用于装饰单元格渲染器,不仅在表格中,而且在comboBox,树,列表中始终如一。