我是第一次使用jtable。如何使 jtable 中的特定行在执行操作后无法再次选择。我尝试了 setRowSelectionAllowed(boolean) 方法,但它适用于所有行。
最佳答案
将表选择模型设置为列表选择模型,不允许选择禁止的行:
class RestrictedSelector extends DefaultListSelectionModel {
HashSet<Integer> forbiddenRows = new HashSet<Integer>();
@Override
public void addSelectionInterval(int index0, int index1) {
for (int row = index0; row <= index1; row++) {
if (forbiddenRows.contains(row)) {
// You can also have more complex code to select still
// valid rows here.
return;
}
}
}
// Implement these in the same spirit:
public void insertIndexInterval(int index0, int index1)
...
public void setSelectionInterval(int index0, int index1)
...
public void setLeadSelectionIndex(int leadIndex)
...
// and others, see below.
}
检查here对于必须重写的所有方法。
现在:
RestrictedSelector selector = new RestrictedSelector();
selector.forbiddenRows.add(NOT_THIS_ROW_1);
selector.forbiddenRows.add(NOT_THIS_ROW_2);
myTable.setSelectionModel(selector);
如果您的表行是可排序的,您可能还需要使用 convertRowIndexToModel
和 convertRowIndexToView
,因为可能是模型中的行号,而不是表中的行号,必须禁止选择。
关于java - 如何使jtable中的一行不可选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15586118/