找到已调用弹出菜单的JTable行 [英] Find the JTable row on which a popup menu has been invoked

查看:85
本文介绍了找到已调用弹出菜单的JTable行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JTable和一个特定于每一行的弹出菜单。我想计算用户右键单击鼠标的行(Windows L& F)以显示弹出菜单。

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.

我为表创建一个MouseListener ,因此它在点击时获取MouseEvent,并在正确的位置显示弹出菜单。但是当用户从弹出菜单中选择一个项目时,我无法确定一种方法来确定用户在第一个位置右键单击的行。弹出菜单调用的事件没有右键单击发生的x,y坐标。

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.

我看到了获取位置的位置弹出窗口,但它属于框架,而不属于表格,所以它和它的父母都没有正确的x,y值我想要的。

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.

我是通过继承JPopupMenu并设置我希望它在MouseListener中拥有的x和y值来解决它。但在我看来,对于想要在JTable上放置弹出菜单的人来说,这将是一个普遍的问题,我想知道我错过了什么。

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.

有没有更简单的方法,尤其是不涉及子类化JPopupMenu的方法?

Is there a simpler way to do this, especially one that doesn't involve subclassing JPopupMenu?

推荐答案

JTable.rowAtPoint(...);

你可以从MouseEvent获得积分。

You can get the point from the MouseEvent.

编辑:

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());
        }
    }
});

这篇关于找到已调用弹出菜单的JTable行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆