我用TableCellRenderer和TableCellEditor添加了一个checkBox表列。 代码如下:
class PanelCellEditorRenderer extends AbstractCellEditor implements
TableCellRenderer, TableCellEditor {
private static final long serialVersionUID = 1L;
private JCheckBox checkBox = new JCheckBox();
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
checkBox.setSelected((boolean)value);
checkBox.setHorizontalAlignment(SwingUtilities.CENTER);
//table.addRowSelectionInterval(row,row);
/* if(val)
table.addRowSelectionInterval(row,row);
else
table.removeRowSelectionInterval(row,row);*/
System.out.println("row::"+row+" column::"+column+" isSelected::"+value);
return checkBox;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
checkBox.setSelected((boolean)value);
checkBox.setHorizontalAlignment(SwingUtilities.CENTER);
/* if(!isSelected)
table.addRowSelectionInterval(row,row);
else
table.removeRowSelectionInterval(row,row);*/
table.getValueAt(row,column);
return checkBox;
}
@Override
public Object getCellEditorValue() {
return checkBox.isSelected();
}
@Override
public boolean isCellEditable(EventObject anEvent) {
return true;
}
@Override
public boolean shouldSelectCell(EventObject anEvent) {
return false;
}
}
我希望在选中复选框时选择表中的相应行。如果未选中CheckBox,则表中相应的行也会被取消选中。当鼠标单击另一行时,所选行的状态不会更改。可以通过重写cellrenderer和cellEditor方法来实现吗?