如何实现改变JTable中的曾选中过的cell的背景

 

2006/5/14

扩展一个JTable,增加一个List记录每次点击选择的cell,将其index记录.然后用一个Renderer,如果cell被选择过,则修改背景颜色为红色.使用时候先实例化一个MyTable,在setCellRenderer.

public class MyTable extends JTable {

private ArrayList selected;

public MyTable() {
super();
selected = new ArrayList();

}
//将选中的cell列,行数记录
public void addSelected(Point p){
if(selected.contains(p)){
selected.remove(p);
}else{
selected.add(p);
}
}

//某个cell是否被记录过

public boolean hasSelected(int row, int column) {
return selected.contains(new Point(row,column));
}

}
实现一个renderer,当cell的index在记录历史中,则修改其背景

public class MyRenderer extends DefaultTableCellRenderer{
public MyRenderer(){
super();
setHorizontalAlignment(SwingConstants.CENTER);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
MyTable mt = (MyTable)table;
if(isSelected){
mt.addSelected(new Point(row,column));
}
if(mt.hasSelected(row,column)){
this.setBackground(Color.RED);
}else{
this.setBackground(Color.WHITE);
}
return this;
}
}

Comments are closed.