我的问题是如何更改 Java 中 JTable 中特定单元格的颜色?据我所知,我应该做的第一件事是重写方法 CellRendered 我已经完成了这部分,如下所示:
public class CustomTableCellRenderer extends DefaultTableCellRenderer
{
int amount;
int f,c;
public CustomTableCellRenderer(int a)
{
amount = a;
}
public CustomTableCellRenderer()
{
}
@Override
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);
if(amount == 3)
{
cell.setBackground(Color.LIGHT_GRAY);
}
if(amount == 1)
{
cell.setBackground(Color.cyan);
}
if(amount == 2)
{
cell.setBackground(Color.orange);
}
return cell;
}
}
当我想更改单元格的颜色时,我更改了颜色,但它更改了整个列,我使用覆盖的代码部分如下:
Cache_table.getColumnModel().getColumn(columna).setCellRenderer(new CustomTableCellRenderer(1));
如何指定要更改颜色的单元格的确切位置,指定行数和列数:
例如:
新的 CustomTableCellRenderer(int 行,int 列);
这可能吗?
谢谢大家...
最佳答案
考虑使用else if
语句,然后在默认的最后一个else block 中添加默认值。
另外,这是关键,不要在渲染器的构造函数中设置 amount - 这是行不通的。相反,您必须在 getTableCellRendererComponent
方法内获取金额结果,通常从单元格的值或同一行上另一个模型单元格的值获取。
@Override
public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererCo
// check that we're in the right column
if (column != correctColumn) {
// if not the right column, don't change cell
return cell;
}
// SomeType is the type of object held in the correct column
SomeType someType = (SomeType) value;
if (value == null) {
value = "";
return cell;
}
// and hopefully it has a method for getting the amount of interest
int amount = someType.getAmount();
if(amount == 3) {
cell.setBackground(Color.LIGHT_GRAY);
} else if(amount == 1) {
cell.setBackground(Color.cyan);
} else if(amount == 2) {
cell.setBackground(Color.orange);
} else {
cell.setBackground(null); // or a default background color
}
此外,您可能需要确保您的单元格是不透明的。
关于java - 如何更改 JTable (JAVA) 中特定单元格的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27215585/