I made this CustomCellRenderer
class intended to be used in JXTreeTable
and JXTable
objects since I have many of these in my project. So this class implements TreeCellRenderer
and TableCellRenderer
interfaces:
public class CustomCellRenderer extends JLabel
implements TreeCellRenderer, TableCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
setBackground(selected ? new Color(83,142,213) : Color.white);
setForeground(selected ? Color.white : Color.black);
//here is the icon setting code but it's irrelevant to my problem
setText(value != null ? value.toString() : "<null>");
return this;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setBackground(isSelected ? new Color(83,142,213) : Color.white);
setForeground(isSelected ? Color.white : Color.black);
setText(value != null ? value.toString() : "<null>");
return this;
}
}
And here is the code where I set the renderer:
jXTreeTableConsumos.setDefaultRenderer(Object.class, new CustomCellRenderer());
jXTreeTableConsumos.setTreeCellRenderer(new CustomCellRenderer());
I'm expecting background and foreground become blue and white respectively when a row is selected. However it only happens at Tree table cell (first column) while only foreground changes and background stills white in the other cells in the very same selected row:
Could anybody please tell me why cells (that are not tree cells) don't change their background color?
Thanks everybody for your comments and suggestions. I found the solution in JComponent#setBackground(Color bg)
documentation:
Sets the background color of this component. The background color is used only if the component is opaque, and only by subclasses of JComponent or ComponentUI implementations. Direct subclasses of JComponent must override paintComponent to honor this property.
Since my CustomCellRenderer
extends from JLabel
the only thing I have to do is make sure it's opaque and its background color will be painted:
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setOpaque(true);//adding this line I solved my problem
setBackground(isSelected ? new Color(83,142,213) : Color.white);
setForeground(isSelected ? Color.white : Color.black);
setText(value != null ? value.toString() : "<null>");
return this;
}
来源:https://stackoverflow.com/questions/18253881/custom-tablecellrenderer-treetablecellrenderer-doesnt-render-table-cells