1
我想更改JTable中單元格的顏色。我編寫了自己的擴展DefaultTableCellRenderer的類。但是,我的班級真的很無情。它所做的只是如果一個條目在列中出現兩次,它會將其標記爲紅色。這是結果我得到:更改JTable中單元格的顏色
注意在這個班,我還設置字體特定列。這工作正常。我想知道爲什麼當我試圖簡單地設置顏色時會出現這種情況。
這裏是我的類:
/*
* 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;
}
}