Ans)
You can think of the renderer as a configurable ink stamp that the table uses to
stamp appropriately formatted data onto each cell. When the user starts to edit
a cell's data, a cell editor takes over the cell, controlling the cell's editing
behavior.
To choose the renderer that displays the cells in a column, a table first determines
whether you specified a renderer for that particular column.
Here are some data type which could be rendered as follows.
Boolean — rendered with a check box.
Number — rendered by a right-aligned label.
You have to override "DefaultTableCellRenderer.getTableCellRendererComponent()"
CellRenderer Example :
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class YourOwnJTableCellColorRenderer extends
DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
private int color = 0;
private int colorPrevious = 0;
private boolean hasHeader = false;
private String tooltip = "";
public static Color TABLE_ALTERNATING_ROW_COLOR = new Color(236,236,244);
public static Color TABLE_GROUP_ROW_COLOR = new Color(236,236,244);
public static Color TABLE_SUMMARY_ROW_COLOR = Color.lightGray;
public YourOwnJTableCellColorRenderer (boolean hasHeader){
super();
this.hasHeader = hasHeader;
}
public YourOwnJTableCellColorRenderer (){
super();
}
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component comp = super.getTableCellRendererComponent(table,value,isSelected,false,row,column);
setForeground(Color.black);
if(row == 0 && hasHeader){
setBackground(TABLE_SUMMARY_ROW_COLOR);
}else if(row%2==0){
setBackground(TABLE_ALTERNATING_ROW_COLOR);
} else{
setBackground(Color.white);
}
if (table.isCellEditable(row, column)) {
if(table.getEditorComponent() instanceof JComboBox){
((JComboBox)table.getEditorComponent()).setBorder(new LineBorder(Color.lightGray,2));
((JComboBox)table.getEditorComponent()).getComponent(1).setFont(new Font("SansSerif", 1, 11));
}
}
Color back = getBackground();
boolean colorMatch = (back != null) && (back.equals(table.getBackground()))
&& table.isOpaque() && (color == colorPrevious);
setOpaque(!colorMatch);
colorPrevious = color;
return comp;
}
public String getTooltip() {
return tooltip;
}
public void setTooltip(String tooltip) {
this.tooltip = tooltip;
}
}