javaswingjtablemouselistenerlistselectionlistener

Using CTRL+CLICK to select multiple rows in JTable


I have a JTable with MULTIPLE_INTERVAL_SELECTION. I need the CONTROL+CLICK to select addition rows. In my LAF, this does not happen automatically. I wrote the following code that uses a mouse listener:

addMouseListener(new MouseAdapter()
{
    @Override
    public void mousePressed(MouseEvent event)
    {
        ListSelectionModel listSelectionModel = getSelectionModel();

        if (listSelectionModel.getSelectionMode() ==
                ListSelectionModel.MULTIPLE_INTERVAL_SELECTION)
        {
            if (event.isControlDown())
            {
                int rowView  = rowAtPoint(event.getPoint());

                if (isRowSelected(rowView))
                {
                    System.out.println("rowView already selected");

                }

                listSelectionModel.addSelectionInterval(rowView, rowView);
            }
        }
    }
});

The problem is that the row selection event happens before the mouse listener is entered. The row that was clicked on is selected, but the previous selections were cleared.

My questions are:

How do I capture the selection event to by-pass automatic selection?

Could I capture that event to stop it from clearing the previous selections, use getModifiers() to see if the CONTROL key was pressed, and call addSelectionInterval?

I need assistance identifying and setting up a listener to do this.


Solution

  • One of my mouse listeners was clearing the selections which made it appear that the control+click was not working. Thanks for reviewing my issue.