JTable right-click row selection

By default a left mouse click on a JTable row will select that row, but it’s not the same for the right mouse button. It takes bit more work to get a JTable to select a row based on right mouse clicks. You might be able to do it by subclassing JTable or ListSelectionModel, but there’s an easier way.

1. Use a MouseAdapter to detect right clicks on the JTable. 2. Get the Point (X-Y coordinate) of the click. 3. Find out what row contains that Point 4. Get the ListSelectionModel of the JTable and 5. Tell the ListSelectionModel to select that row. Here’s what it looks like:

table.addMouseListener( new MouseAdapter() { public void mousePressed( MouseEvent e ) { // Left mouse click if ( SwingUtilities.isLeftMouseButton( e ) ) { // Do something } // Right mouse click else if ( SwingUtilities.isRightMouseButton( e ) { // get the coordinates of the mouse click Point p = e.getPoint();   // get the row index that contains that coordinate int rowNumber = table.rowAtPoint( p );   // Get the ListSelectionModel of the JTable ListSelectionModel model = table.getSelectionModel();   // set the selected interval of rows. Using the “rowNumber” // variable for the beginning and end selects only that one row. model.setSelectionInterval( rowNumber, rowNumber ); } } });

Alternately, you can use e.isPopupTrigger() in place of SwingUtilities.isRightMouseButton( e ) if you are wanting to bring up a JPopupMenu in response to the click.

Scroll to Top