NickW
NickW

Reputation: 1343

JTable mouse listener on row example

I've taken this code from another question and was hoping someone could clarify a couple of points:

table.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseReleased(MouseEvent e) {
        int r = table.rowAtPoint(e.getPoint());
        if (r >= 0 && r < table.getRowCount()) {
            table.setRowSelectionInterval(r, r);
        } else {
            table.clearSelection();
        }

        int rowindex = table.getSelectedRow();
        if (rowindex < 0)
            return;
        if (e.isPopupTrigger() && e.getComponent() instanceof JTable ) {
            JPopupMenu popup = createYourPopUp();
            popup.show(e.getComponent(), e.getX(), e.getY());
        }
    }
});

i understand that the line that defines 'r' gets the row at the mouse event point. but why is 'rowindex' initialised using table.getSelectedRow()? why not just use the variable 'r'. aren't they the same thing?

also - i'm confused by e.isPopupTrigger(). i read the documentation, and it refers to it as returning whether the mouseevent is the trigger for the popup.... the trick is obviously in the name - but i'm unsure of what conditions make it true or false (especially as popup.show(), whose first parameter is the invoker, is inside the if statement).

sorry for the confusion, i just don't want to blindly copy the code!

thanks

Upvotes: 0

Views: 2788

Answers (1)

camickr
camickr

Reputation: 324118

but why is 'rowindex' initialised using table.getSelectedRow()? why not just use the variable 'r'.

The code is checking to see if the mouse point is after the last row in the table. This can happen when you use:

table.setFillsViewportHeight(true);

and your table data doesn't completely fill all the rows in the viewport of the scrollpane.

So if you click after the last row the rowAtPoint(...) method will return -1, which will be different than the row returned by getSelectedRow().

This will cause the row selection to be removed.

Now you can use the getSelectedRow() method to determine if you have a selected row and therefore display the popup.

i'm confused by e.isPopupTrigger().

The MouseEvent used to display the popup can be different for different platforms.

Upvotes: 2

Related Questions