gpt4 book ai didi

java - 我必须选择该复选框两次才能在 jTable 中选中/取消选中

转载 作者:行者123 更新时间:2023-12-02 08:33:42 26 4
gpt4 key购买 nike

我有一个打算使用的 jTable 代码,但问题是,当我单击复选框时,它不会选择/取消选择它,而是必须单击两次。但是,如果我选择该行中除包含复选框的单元格之外的任何其他单元格,目的就解决了。

这是我的代码:

public class TableSelectionTest extends JFrame implements ListSelectionListener {
private final int COLUMN_COUNT = 5;
private TblModel model;
public TableSelectionTest() {
initialize();
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
private void initialize() {
List data = new ArrayList();
for (int i = 0; i < 10; i++) {
Object record[] = new Object[COLUMN_COUNT];
record[0] = Boolean.FALSE;
for (int j = 1; j < COLUMN_COUNT; j++)
{
record[j] = new Integer(j);
}
data.add(record);
}
model = new TblModel(data);
JTable table = new JTable(model);
table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener (this);
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll, BorderLayout.CENTER);
}

public static void main(String[] args) {
TableSelectionTest f = new TableSelectionTest();
f.show();
}

class TblModel extends AbstractTableModel {
private List data;
public TblModel(List data) {
this.data = data;
}
public int getColumnCount() {
return COLUMN_COUNT;
}
public int getRowCount() {
return data == null ? 0 : data.size();
}
public void setValueAt(Object value, int rowIndex, int columnIndex) {
getRecord(rowIndex)[columnIndex] = value;
super.fireTableCellUpdated(rowIndex, columnIndex);
}
public Object getValueAt(int rowIndex, int columnIndex) {
return getRecord(rowIndex)[columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
if(columnIndex == 0)
return true;
else
return false;
}
public Class getColumnClass(int columnIndex) {
if (data == null || data.size() == 0) {
return Object.class;
}
Object o = getValueAt(0, columnIndex);
return o == null ? Object.class : o.getClass();
}
private Object[] getRecord(int rowIndex) {
return (Object[]) data.get(rowIndex);
}
}

public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
int index = lsm.getMinSelectionIndex();
if(model.getRecord(index)[0] == Boolean.FALSE)
model.setValueAt(Boolean.TRUE, index, 0);
else if(model.getRecord(index)[0] == Boolean.TRUE)
model.setValueAt(Boolean.FALSE, index, 0);
}
}
}

请尽快回复,因为这让我很烦恼预先感谢您:)

最佳答案

您的 ListSelectionListener 与您的 TableCellEditor 冲突。

理想情况下,我建议删除 ListSelectionListener。这不是必需的,因为 TableCellEditor 只是调用 setValueAt() 来更新单元格的内容。

关于java - 我必须选择该复选框两次才能在 jTable 中选中/取消选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541037/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com