更改JTable中单元格的颜色 [英] Changing color of cell in JTable
问题描述
我想更改JTable中单元格的颜色.我编写了自己的类,该类扩展了DefaultTableCellRenderer.但是,我的班级的行为确实很不协调.它所要做的就是,如果某项在列中出现两次,则将其标记为红色.这是我得到的结果:
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:
请注意,在此类中,我还将为特定列设置字体.很好我想知道为什么在尝试简单地设置颜色时会出现这种现象.
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.
这是我的课程:
/*
* 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;
}
}
推荐答案
DefaultTableCellRenderer是一个特别糟糕的实现-您发现它是臭名昭著的彩色内存".要变通,您必须始终设置其颜色属性
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)
或更好(当然有偏见):在SwingX中使用JXTable,它具有完全可插拔的支持来装饰单元格渲染器,不仅在表格中,而且在comboBox,tree,list中也一致.
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 ..
这篇关于更改JTable中单元格的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!