How to select only the first cell of every row in a jtable, one at a time while the other cells cant be selected

StackOverflow https://stackoverflow.com/questions/22917572

  •  29-06-2023
  •  | 
  •  

Question

How can I select only the first cell of every row in a jtable, one at a time while the other cells cant be selected?

My code is:

        jTable5.addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent e){

    int i=jTable5.getSelectedColumn();
    System.out.println(i);
    if(i==0)
    {  
        jTable5.setCellSelectionEnabled(true);
         jTable5.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

    }
    else{
        jTable5.setCellSelectionEnabled(false);
    }
}

});

Still,while moving on the cell of second column,it first select that cell and then deselect it.

Was it helpful?

Solution

First, disable row selection:

setRowSelectionAllowed(false);

Second, create a SelectionListener, which always move the selection to the first column of row:

ListSelectionListener listerner = new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
          setColumnSelectionInterval(0, 0);
       }
    };

And finally add the listener to your table's Column Selection Model

getColumnModel().getSelectionModel().addListSelectionListener(listerner);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top