我需要确保仅选中列中的一个复选框。所以,当用户选择复选框时,我必须取消选择以前选择的。
我尝试在 TableModel 的 setValueAt 方法中执行此操作,但我无法更新单元格,即使是通过按钮单击的单元格也是如此。我没有显示我的所有代码,而是创建了简单的示例来帮助尝试解决方案:
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();
}
}
所以,我希望 Vegeterian 列只选择一个复选框,当用户选择一个复选框时,另一个应该被取消选中。
谢谢!