JTable上的JPopupMenu - >获取创建菜单的单元格 [英] JPopupMenu on JTable -> Get the cell the menu was created on
问题描述
我有一种情况,我在右键单击JTable时创建了一个弹出菜单。创建弹出菜单的标准方法:
I have a situation where I have a popup menu created when a JTable is right clicked on. Standard way of creating the popup menu:
aJTable.setComponentPopupMenu(rightClickMenu);
现在,在注册的操作中,我无法找到右键单击的单元格让弹出菜单出现。
Now afterwards in the action that gets registered, I am unable to find out which cell was right clicked on to get that popup menu to appear.
rightClickMenuItem.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// Work out what cell was right clicked to generate the menu
}
});
关于你如何做的任何想法?
Any ideas on how you do this?
推荐答案
@MadProgrammer对getPopupLocation的建议看起来很有希望,但我无法弄清楚如何在表和actionEvent之间获取信息......
@MadProgrammer's suggestion of getPopupLocation looked promising, but I couldn't work out how to get the information across between the table and the actionEvent...
我通过确保在右键单击时选择了行来解决这个问题 - >因为弹出菜单阻止了行的选择,你可以添加一个鼠标监听器来确保行获得无论点击什么(左或右)都被选中。
I got around this by making sure that the row was selected when you rightclicked on it -> since the popup menu prevents the selection of the row, you can add in a mouse listener that makes sure the row gets selected no matter what click (left or right) is pressed.
aTable.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int r = aTable.rowAtPoint(e.getPoint());
if (r >= 0 && r < clt.getRowCount()) {
aTable.setRowSelectionInterval(r, r);
} else {
aTable.clearSelection();
}
}
});
这意味着在rightClickMenuItem的动作侦听器中,您可以获取表格的选定单元格/行
This means that in the rightClickMenuItem's action listener, you can grab the table's selected cell / row
rightClickMenuItem.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
aTable.get details about the selected one....
}
});
太简单了!谢谢大家的帮助。
Too easy! Thanks everyone for the help.
这篇关于JTable上的JPopupMenu - >获取创建菜单的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!