2

I have written a "double-click" event on my JTable. My JTable, viz. myTaskTable is populated with a number of rows having multiple columns. I want the row index to be retrieved when I double click on one of the rows of the JTable. I am not sure why is it always returning me an index of -1 resulting in an exception. Am I am overlooking something? What could be going wrong?

This is how I am retrieving the index of the selected row from the JTable - myTaskTable

int selRow = myTaskTable.getSelectedRow();

Thank you!

Edit

Here is the code:

...
myTaskTable.addMouseListener(this);
...
public void mouseClicked(MouseEvent e)
{
 if(e.getModifiers() == MouseEvent.BUTTON1_MASK)
 {
   if(e.getClickCount() == 2)
   {
     e.consume();
     int selRow = myTaskTable.getSelectedRow();
     System.out.println("GridReport double clicked on row="+selRow);
    }
  }
}
user1639485
  • 808
  • 3
  • 14
  • 26
  • 4
    I think that your problem is in code that you've not shown us. Our abilities to guess about errors in code not shown is quite limited. – Hovercraft Full Of Eels Sep 30 '12 at 18:56
  • For reference, here's a workign [example](http://stackoverflow.com/a/11241218/230513). – trashgod Sep 30 '12 at 19:01
  • What is the `e.consume()` for? Also, is the myTaskTable variable referring to the JTable that is in fact being displayed? For better help, consider creating and posting an [sscce](http://sscce.org). This will require a bit of effort, but is often well worth it. – Hovercraft Full Of Eels Sep 30 '12 at 19:04

2 Answers2

3

Get the row index using the event, not the table selection:

final int selectedRowIndex = table.rowAtPoint(mouseEvent.getPoint());
// If the rows are sorted or filtered
final int modelRowIndex = table.convertRowIndexToModel(selectedRowIndex);

getSelectedRow() would not work with multiple selected rows (multiple selections allowed), as it will always return "the index of the first selected row".

Eddie G.
  • 2,344
  • 2
  • 17
  • 7
0

have you tried to put e.consume(); as the last statement?

public void mouseClicked(MouseEvent e){
 if(e.getModifiers() == MouseEvent.BUTTON1_MASK){
   if(e.getClickCount() == 2){
     int selRow = myTaskTable.getSelectedRow();
     System.out.println("GridReport double clicked on row="+selRow);
     e.consume();
    }
  }
}

normaly e.consume(); is called when you are done with your reactive code. This clears dependencies of the Event, so it might also clear the selected Row.

Simulant
  • 19,190
  • 8
  • 63
  • 98