开发者

Find the JTable row on which a popup menu has been invoked

开发者 https://www.devze.com 2023-01-23 18:34 出处:网络
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 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 开发者_JAVA技巧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());
        }
    }
});


If you don't mind selecting your row on right button click, then in the MouseListener use JTable.rowAtPoint() and select the row if it's not selected, and then in the popup listener use JTable.getSelectedRows() to process your rows. Or you can save them in a separate data structure that you can access from your popup menu listener.

0

精彩评论

暂无评论...
验证码 换一张
取 消