我正在使用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();
}
});
}
}
这段代码无法处理多个禁用列或跨越多个列的选择。您需要修改它以处理这些情况。
使用setColumnSelectionAllowed(false);
并将您喜欢的列设置为它,应该可以解决问题。我在最近的JTable项目中使用了这个方法。
“列选择”控制columnSelectionAllowed
,它具有setter方法setColumnSelectionAllowed
和getter方法getColumnSelectionAllowed
。当此绑定属性为true
(且rowSelectionAllowed
绑定属性为false
)时,用户可以按列选择。
来自http://download.oracle.com/javase/tutorial/uiswing/components/table.html