Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make one entire column unselectable in java?

Tags:

java

swing

jtable

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?

like image 368
octoberqueen Avatar asked Nov 26 '25 13:11

octoberqueen


2 Answers

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.

like image 136
Azmisov Avatar answered Nov 29 '25 01:11

Azmisov


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

like image 26
Handsken Avatar answered Nov 29 '25 02:11

Handsken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!