[英]Changing colour of specific cell in a JTable
我正在尝试更改JTable列中一个或多个特定单元格的颜色。 我在这里看到的答案都是关于这种特定方法的。
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component y = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
y.setBackground(new Color(255,0,0));
return y;
}
但是问题是我完全不知道它是如何工作的,在我的另一堂课中,我有一个字符串Jtable,我想根据它们的字符串值更改某些单元格的颜色,但是我发现的解决方案只允许我更改jtable中整个单元格的颜色,而不是特定的颜色。
我有一个字符串Jtable,我想根据它们的字符串值更改某些单元格的颜色
所有单元都使用相同的渲染器,因此您每次都需要重置背景。
您的自定义渲染器代码中将需要一个if条件。 就像是:
if (!isSelected)
if (value.equals(...))
y.setBackground(new Color(255,0,0));
else
y.setBackground(table.getBackground())
您可以使用DefaultTableCellRenderer为JTable的备用行着色。
table.setDefaultRenderer(Object.class, new TableCellRenderer(){
private DefaultTableCellRenderer DEFAULT_RENDERER = new DefaultTableCellRenderer();
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = DEFAULT_RENDERER.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(isSelected){
c.setBackground(Color.YELLOW);
}else{
if (row%2 == 0){
c.setBackground(Color.WHITE);
}
else {
c.setBackground(Color.LIGHT_GRAY);
} }
//Add below code here
return c;
}
});
如果要使用特定行的值为行着色,则可以使用类似的内容。 将这些行添加到上面
if(table.getColumnModel().getColumn(column).getIdentifier().equals("Status")){//Here `Status` is column name
if(value.toString().equals("OK")){//Here `OK` is the value of row
c.setBackground(Color.GREEN);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.