我正在使用netbeans执行我的Java项目。我想使除一列之外的整个列都无法选择。用户应该只能单击一列中的行。怎么做?
您可以将ListSelectionListener添加到表中。如果当前选择是不可选择的列,则可以撤消选择。这是一个例子:
public class MyTable extends JTable(){
//the column to disable
//... and the currently selected column
private int disabled_col = 2, cur_col = 0;
public MyTable(){
//Create a column selection listener
final ListSelectionModel sel = this.getColumnModel().getSelectionModel();
sel.addListSelectionListener(new ListSelectionListener(){
@Override
public void valueChanged(ListSelectionEvent e) {
//If the column is disabled, reselect previous column
if (sel.isSelectedIndex(disabled_col))
sel.setSelectionInterval(cur_col,cur_col);
//Set current selection
else cur_col = sel_mod1.getMaxSelectionIndex();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
此代码无法处理多个禁用的列或跨越多个列的选择。您必须对其进行修改才能处理这些情况。
| 归档时间: |
|
| 查看次数: |
2774 次 |
| 最近记录: |