So I have this table:
table = new JTable();
Which models my model: table.setModel(model);
Inside I have a column called CheckColumn which has only CheckBoxes.
The thing is that if I check one box, it checks it and if I want to check another one, it removes the previous check. So it lets me check only one checkbox.
For the checkboxes I'm using the following:
table.getColumnModel().getColumn(15).setCellEditor(new CheckBoxCellEditor());
table.getColumnModel().getColumn(15).setCellRenderer(new CWCheckBoxRenderer());
From the Classes:
class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor {
private static final long serialVersionUID = 1L;
protected JCheckBox checkBox;
public CheckBoxCellEditor() {
checkBox = new JCheckBox();
checkBox.setHorizontalAlignment(SwingConstants.CENTER);
checkBox.setBackground(Color.white);
}
public Component getTableCellEditorComponent(
JTable table,
Object value,
boolean isSelected,
int row,
int column) {
checkBox.setSelected(((Boolean) value).booleanValue());
Component c = table.getDefaultRenderer(String.class).getTableCellRendererComponent(table, value, isSelected, false, row, column);
if (c != null) {
checkBox.setBackground(c.getBackground());
}
return checkBox;
}
public Object getCellEditorValue() {
return Boolean.valueOf(checkBox.isSelected());
}
}
And:
class CWCheckBoxRenderer extends JCheckBox implements TableCellRenderer {
public CWCheckBoxRenderer() {
super();
setOpaque(true);
setHorizontalAlignment(SwingConstants.CENTER);
}
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
if (value instanceof Boolean) {
setSelected(((Boolean)value).booleanValue());
setEnabled(table.isCellEditable(row, column));
if (isSelected) {
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
}
else {
setSelected(true);
setEnabled(true);
return null;
}
return this;
}
}
I want to be able to check more than one row. Can someone tell me how can I do that? Is there something to be modified in the code or I need a new approach?
This is a summary of how the model looks like:
private static final int CheckCol = 15;
private List<Clients> clients;
public boolean isCellEditable(int row, int col){
if(col == 15){
return true;
}
return false;
}
public void setValueAt(Object value, int row, int col) {
//if(col==15) (not sure what to do in here)
//fireTableCellUpdated(row, col);
}
public Object getValueAt(int row, int col) {
Clients tempClient = clients.get(row);
switch (col) {
case CheckCol:
return false; //my CheckColumn type is Boolean
default:
return false;
}
}
I've tried everything I could think of to change the model...Can someone tell me how should the model look like? I need to get data from a mysql server and I don't know how to model the checkbox column.
Thanks in advance!