Post by pljosh(at)poczta_neostrada_plWyglada to wiec jednak chyba trywialnie (o ile to zadziala)
mojaTabelka.getCellRenderer(2,3).setBackground(Color(GREEN));
Nie sprawdzalem, ale to moze byc to :)
kiedyś zdarzyło mi się napisać taki CellRenderer, którego tło zależy od
przechowywanej wartośći (w moim przypadku wartość to obiekt klasy
org.apache.log4j.Priority).
Z tego co pamiętam, to nie było to całkiem trywialne (kod przedstawiam
poniżej, może do czegoś Ci się przyda).
ZTCP musiałem przepisać kawałek oryginalnej implementacji tej klasy ze
źródeł javy, bo inaczej coś tam nie grało. W każdym razie poniższa
klasa działa poprawnie (jest częścią projektu chainsaw - przeglądarki
logów generowanych przez log4j).
Pozdrawiam
Bartek
package com.puppycrawl.tools.chainsaw;
import javax.swing.table.*;
import javax.swing.*;
import org.apache.log4j.Category;
import org.apache.log4j.Priority;
import java.awt.*;
public class PriorityFieldCellRenderer extends DefaultTableCellRenderer
{
private Color unselectedForeground;
private Color unselectedBackground;
protected void setValue(Object value) {
super.setValue(value);
}
public Component getTableCellRendererComponent(JTable table, Object
value, boolean isSelected, boolean hasFocus, int row, int column) {
Priority priority = (Priority)value;
Color priorityColor = null;
if (priority.equals(Priority.FATAL))
priorityColor = Color.red;
else if (priority.equals(Priority.ERROR))
priorityColor = Color.orange;
else if (priority.equals(Priority.WARN))
priorityColor = Color.yellow;
if (isSelected) {
super.setForeground(table.getSelectionForeground());
if (priorityColor!=null)
super.setBackground(priorityColor.darker());
else
super.setBackground(table.getSelectionBackground());
}
else {
super.setForeground((unselectedForeground != null) ?
unselectedForeground : table.getForeground());
if (priorityColor!=null)
super.setBackground(priorityColor);
else
super.setBackground((unselectedBackground != null) ?
unselectedBackground : table.getBackground());
}
setFont(table.getFont());
if (hasFocus) {
setBorder(
UIManager.getBorder("Table.focusCellHighlightBorder") );
if (table.isCellEditable(row, column)) {
super.setForeground(
UIManager.getColor("Table.focusCellForeground") );
super.setBackground(
UIManager.getColor("Table.focusCellBackground") );
}
} else {
setBorder(noFocusBorder);
}
setValue(value);
return this;
}
public void setForeground(Color c) {
super.setForeground(c);
unselectedForeground = c;
}
public void setBackground(Color c) {
super.setBackground(c);
unselectedBackground = c;
}
}