如何更改JTable(JAVA)中特定单元格的颜色?
我的问题是如何在Java中更改JTable中特定单元格的颜色?据我所知,我应该做的第一件事是重写CellRendered方法,我已经按照如下方式完成了这一部分:如何更改JTable(JAVA)中特定单元格的颜色?,java,swing,colors,jtable,tablecellrenderer,Java,Swing,Colors,Jtable,Tablecellrenderer,我的问题是如何在Java中更改JTable中特定单元格的颜色?据我所知,我应该做的第一件事是重写CellRendered方法,我已经按照如下方式完成了这一部分: public class CustomTableCellRenderer extends DefaultTableCellRenderer { int amount; int f,c; public CustomTableCellRenderer(int a) { amount =
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));
}
当我想改变单元格的颜色时,我改变了颜色,但它改变了整个列,我使用覆盖的代码部分如下所示:
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
语句,然后在default last else块中添加默认值
另外,这是键,不要在渲染器的构造函数中设置数量——这不会起作用。相反,您必须在gettableCellRenderComponent
方法内获得amount结果,通常来自单元格的值,或者来自同一行上另一个模型单元格的值
@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
}
此外,您可能需要确保您的单元格是不透明的