Reputation: 39
I am doing my java project using netbeans. I want to make entire columns except one column unselectable.The user should be only able to click rows in only in one column. How to do that?
Upvotes: 3
Views: 3153
Reputation: 7253
You can add a ListSelectionListener to the your table. If the current selection is the unselectable column, you can undo the selection. Here's an example:
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();
}
});
}
}
This code doesn't handle multiple disabled columns or selections spanning multiple columns. You would have to modify it to handle those cases.
Upvotes: 5
Reputation: 674
Use setColumnSelectionAllowed(false);
and set you prefered column to it, should work.
Think i used that one on my recent project with a JTable.
"Column Selection" controls columnSelectionAllowed
which has setter method setColumnSelectionAllowed
and getter method getColumnSelectionAllowed
. When this bound property is true
(and the rowSelectionAllowed
bound property is false
), the user can select by column.
From http://download.oracle.com/javase/tutorial/uiswing/components/table.html
Upvotes: 1