我想更改JTable中单元格的颜色.我编写了自己的类,扩展了DefaultTableCellRenderer.但是,我的课的行为确实很不协调.它所做的就是,如果某项在列中出现两次,则将其标记为红色.这是我得到的结果:
请注意,在此类中,我还为特定列设置了字体.很好我想知道为什么在尝试简单地设置颜色时会出现这种现象.
这是我的课:
/*
* 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;
}
}