[英]Changing color of cell in JTable
I would like to change the color of a cell in a JTable.我想更改 JTable 中单元格的颜色。 I wrote my own class that extends DefaultTableCellRenderer.
我编写了自己的扩展 DefaultTableCellRenderer 的 class。 However, my class has really inconsitent behavior.
但是,我的 class 的行为确实不一致。 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.请注意,在此 class 中,我还设置了特定列的字体。 That works fine.
这很好用。 I am wondering why I get this behavior when trying to simply set the color.
我想知道为什么在尝试简单地设置颜色时会出现这种行为。
Here is my class:这是我的 class:
/*
* 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 is a particularly bad implementation - you hit it's infamous "color memory". DefaultTableCellRenderer 是一个特别糟糕的实现——你发现它是臭名昭著的“颜色记忆”。 To work around, you have to set its color properties always
要解决此问题,您必须始终设置其颜色属性
if (myCondition)
comp.setBackground(red)
else
comp.setBackground(normal)
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..或者更好(当然是偏袒我):在 SwingX 中使用 JXTable,它提供了对装饰单元格渲染器的完全可插拔支持,不仅在表格中,而且在 comboBox、树、列表中始终如一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.