I need to ensure that only one checkbox in column is selected. So, when user selects checkbox I must unselect previous selected.
I tried to do it in setValueAt method of TableModel but I cannot update cell, even that one which I click by button. I don't show all my code, instead I created simple sample that should help to try out solutions:
public class DateFormatDemo extends JFrame
{
private JTable dataSearchResultTable;
public DateFormatDemo()
{
JPanel panel = new JPanel(new GridLayout(2, 1, 5, 10));
panel.setPreferredSize(new Dimension(500, 300));
dataSearchResultTable = new JTable(new MyTableModel());
dataSearchResultTable.setSelectionBackground(new Color(0xaaaaff));
dataSearchResultTable.setFillsViewportHeight(true);
dataSearchResultTable.setRowSelectionAllowed(true);
dataSearchResultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
dataSearchResultTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
dataSearchResultTable.setRowHeight(25);
panel.add(new JScrollPane(dataSearchResultTable));
super.getContentPane().add(panel);
super.pack();
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.setVisible(true);
}
class MyTableModel extends AbstractTableModel
{
private String[] columnNames = { "First Name", "Last name", "Vegetarian" };
private Object[][] data;
MyTableModel()
{
data = new Object[][] { { "Vova", "KipokKipokKipokKipok", false }, { "Olia", "Duo", true },
{ "Ivan", "Brown", false } };
fireTableDataChanged();
}
public int getColumnCount()
{
return columnNames.length;
}
public int getRowCount()
{
return data.length;
}
public String getColumnName(int col)
{
return columnNames[col];
}
public Object getValueAt(int row, int col)
{
if (data.length > 0 && data[0] != null) {
return data[row][col];
}
return null;
}
public Class getColumnClass(int c)
{
Object valueAt = getValueAt(0, c);
return valueAt == null ? Object.class : valueAt.getClass();
}
public boolean isCellEditable(int row, int col)
{
return true;
}
public void setValueAt(Object value, int row, int col)
{
if (data.length > 0 && data[0] != null) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
}
public static void main(String[] args) throws ParseException
{
new DateFormatDemo();
}
}
So, I want Vegeterian column to have only one checkbox selected and when user selects one checkbox then another should become unselected.
Thank you!