I would like create a jtable with a personal different background color for row. I write the code but I have a problem, if I select the row or if I scroll the table, my personal color configuration is lost.
Thanks to all
this my code
private void go(){
DefaultTableModel dm = (DefaultTableModel)jtLav.getModel();
dm.getDataVector().removeAllElements();
String s_sql = "query";
try{
ConnessionePG con = new ConnessionePG("tifas");
Vector v_res = con.getResult(s_sql);
con.close();
Vector v_last_pos = new Vector();
Vector v_first_pos = new Vector();
String s_car_prec = "";
int i_count_col = 0;
for (int i = 0; i < v_res.size(); i++){
Hashtable ht = (Hashtable) v_res.get(i);
String s_car_att = (String) ht.get("carica");
if (i == 0){
v_first_pos.add(i);
}
else if (s_car_att.equals(s_car_prec) == false){
v_last_pos.add(i-1);
v_first_pos.add(i);
}
if (i == v_res.size() - 1){
v_last_pos.add(i);
}
s_car_prec = s_car_att;
}
for (int i = 0; i < v_res.size(); i++){
TableColumn tc = new TableColumn();
tc.setCellRenderer(new MyTableCellRenderer(v_last_pos));
Hashtable ht = (Hashtable) v_res.get(i);
System.out.println((String)ht.get("fine"));
// dati da inserire
Object o_indice_col = v_first_pos.get(i_count_col);
int i_indice_col = (int) o_indice_col;
if (i_indice_col == i){
i_count_col++;
....
}
dm.addRow(new Object[]{...
});
}
Enumeration<TableColumn> en = jtLav.getColumnModel().getColumns();
while (en.hasMoreElements()) {
TableColumn tc = en.nextElement();
tc.setCellRenderer(new MyTableCellRenderer(v_last_pos));
}
}
catch(SQLException e){
}
}
public class MyTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer {
public MyTableCellRenderer(Vector v){
v_pos_col = v;
System.out.println(v_pos_col);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setBackground(null);
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setText(String.valueOf(value));
Vector v_col = new Vector();
v_col.add(new Color(238,218,226));
v_col.add(Color.white);
Color col_now = null;
try{
Object o_indice_col = v_pos_col.get(i_count_col);
int i_indice_col = (int) o_indice_col;
col_now = (Color)v_col.get(i_col % 2);
setBackground((Color)v_col.get(i_col % 2));
if (row == i_indice_col){
i_count_col++;
i_col++;
}
}
catch(ArrayIndexOutOfBoundsException e){}
return this;
}
int i_col = 0;
int i_count_col = 0;
Vector v_pos_col = new Vector();
}
I solved my problem. I pass to my class an hashtable with each row and its color.