2011-04-28 191 views
1

我想更改JTable中单元格的颜色。我编写了自己的扩展DefaultTableCellRenderer的类。但是,我的班级真的很无情。它所做的只是如果一个条目在列中出现两次,它会将其标记为红色。这是结果我得到:更改JTable中单元格的颜色

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

回答

4

DefaultTableCellRenderer是一个特别糟糕的实现 - 你打它的臭名昭著的 “色记忆”。要解决,你必须设置它的颜色属性总是

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

或更好(偏向我,当然):在SwingX使用JXTable,它自带全可插拔支持装饰单元格渲染器,不仅在一个表,但始终在组合框,树,列表中。