I have a JTable and a popup menu that is specific to each row. I want to calculate the row on which the user right-clicked his mouse (Windows L&F) to bring up the popup menu.
I create a MouseListener for the table, so it gets the MouseEvent at the click, and shows the popup menu at the correct place. But when the user selects one item off the popup menu, I can't figure a way to determine what the row was where the user right-clicked in the first place. The event for the popup menu invocation doesn't have the x,y coordinates where the right-click took place any more.
I've looked at getting the position of the popup, but that belongs to the frame, not the table, so neither it nor its parent have the right x,y values for what I want.
I've worked around it by subclassing JPopupMenu and setting the x and y values I want it to have in the MouseListener. But it seems to me like this would be a general problem for anyone wanting to put a popup menu on a JTable, and I'm wondering what I've missed.
Is there a simpler way to do this, especially one that doesn't involve subclassing JPopupMenu?
JTable.rowAtPoint(...);
You can get the point from the MouseEvent.
Edit:
table.addMouseListener( new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
if (e.isPopupTrigger())
{
JTable source = (JTable)e.getSource();
int row = source.rowAtPoint( e.getPoint() );
int column = source.columnAtPoint( e.getPoint() );
if (! source.isRowSelected(row))
source.changeSelection(row, column, false, false);
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
});