查找已调用弹出菜单的 JTable 行
我有一个 JTable 和一个特定于每一行的弹出菜单。我想计算用户右键单击鼠标(Windows L&F)以调出弹出菜单的行。
我为表创建了一个 MouseListener,因此它可以在单击时获取 MouseEvent,并在正确的位置显示弹出菜单。但是,当用户从弹出菜单中选择一个项目时,我无法找到一种方法来确定用户首先右键单击的行。弹出菜单调用的事件不再具有右键单击发生的 x,y 坐标。
我已经考虑过获取弹出窗口的位置,但它属于框架,而不是表格,因此它或其父级都没有我想要的正确的 x,y 值。
我通过子类化 JPopupMenu 并设置我希望它在 MouseListener 中具有的 x 和 y 值来解决这个问题。但在我看来,这对于任何想要在 JTable 上放置弹出菜单的人来说都是一个普遍问题,我想知道我错过了什么。
有没有一种更简单的方法来做到这一点,尤其是不涉及子类化 JPopupMenu 的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从 MouseEvent 获取点。
编辑:
You can get the point from the MouseEvent.
Edit:
如果您不介意单击右键选择行,则在 MouseListener 中使用 JTable.rowAtPoint() 并选择该行(如果未选择),然后在弹出侦听器中使用 JTable.getSelectedRows() 来处理您的行。或者您可以将它们保存在单独的数据结构中,您可以从弹出菜单侦听器访问该数据结构。
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.