我想更改 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;
}
}
DefaultTableCellRenderer 是一个特别糟糕的实现 - 你会遇到它臭名昭著的“颜色记忆”。要解决此问题,您必须设置其颜色属性always
if (myCondition)
comp.setBackground(red)
else
comp.setBackground(normal)
或更好(当然,对我有偏见):在 Swing 中使用 JTable,它提供了对装饰单元格渲染器的完全可插拔支持,不仅在表格中,而且在组合框、树、列表中始终如一。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)