我的自定义 TableCellRenderer 用于复选框渲染有一个奇怪的问题,它在第一行正常工作,但在其他行上,它设置取消/选中第一次单击和第二次单击之间的所有复选框。这是代码:
/*This Class is meant to be the Concrete Aspect*
* of CheckBox in JTable */
public class CheckItem{
private String label;
private boolean isSelected=false;
public CheckItem(String label){
this.label=label;
}
public boolean isSelected(){
return isSelected;
}
public void setSelected(boolean isSelected){
this.isSelected=isSelected;
}
@Override
public String toString(){
return label;
}
}
现在我使用的渲染器:
/*This Class is a renderer simulating a CheckBox in JTable Column(s)*/
public class CheckTableRenderer extends JCheckBox
implements TableCellRenderer{
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if(value==null){
return null;
}
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
}
else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
CheckItem prov=(CheckItem)value;
if(!prov.toString().equals("")){
this.setText(prov.toString());
}
else
setHorizontalAlignment(CENTER);
this.setSelected(prov.isSelected());
return this;
}
}
最后是 mouseListener 更改值,包含在类 Listeners 中:
public static MouseListener createCheckMouseListener(final JTable table,final int column){
MouseListener m=new MouseAdapter() {
public void mouseClicked(MouseEvent e){
final int x=table.getSelectedRow();
final int y=table.getSelectedColumn();
if((y==column || column==-1)&& y==table.columnAtPoint(e.getPoint())){
try{
CheckItem item=(CheckItem)table.getValueAt(x,y);
item.setSelected(!item.isSelected());
table.repaint(table.getCellRect(x,y,false));
}catch(java.lang.NullPointerException e2){
System.out.println("ERREUR!!!!");
}
}
}
};
return m;
}
及其关联:
mytable.addMouseListener(Listeners.createCheckMouseListener)
;
所有这些代码似乎都是正确的,但关于行的结果并不好,第一个除外。它使用布尔值而不是 CheckItem 工作,但我需要在复选框中放置一个字符串。我无法修复它,我什至想知道问题是否出在这些部分......你能帮我吗?
谢谢。
这是一个例子:SSCCE