【问题标题】:How can I select a list/tree/table item via right-click and open a context menu at the same time?如何通过右键单击选择列表/树/表格项目并同时打开上下文菜单?
【发布时间】:2020-11-24 08:57:22
【问题描述】:
当我右键单击 Swing 表/树/列表中的项目时,
- 该项目应该被选中并且
- 应显示适当的 JPopupMenu(上下文菜单)。
我怎样才能做到这一点?
我正在使用component.setComponentPopupMenu(popupMenu) 为我的组件注册弹出菜单,这似乎吞噬了右键单击事件,因此永远不会选择目标项目。
【问题讨论】:
标签:
java
swing
user-interface
jtable
contextmenu
【解决方案1】:
这里的问题是右键单击确实被内置的弹出触发器消耗了。
为了解决这个问题,覆盖 JPopupMenu.show(...) 这样的方法(JTable、JList 和 JTree 的示例工作类似):
public class ExtJPopupMenu extends JPopupMenu {
[...]
@Override
public void show(final Component invoker, final int x, final int y) {
if (invoker instanceof JTable) {
final JTable table = (JTable) invoker;
final int selRow = table.rowAtPoint(new Point(x, y));
if (selRow > -1 && !table.getSelectionModel().isSelectedIndex(selRow)) {
table.getSelectionModel().setSelectionInterval(selRow, selRow);
}
}
// ensure the newly selected item is focused
invoker.requestFocus();
// now build the appropriate menu for the selected item
[...]
// finally show the menu
super.show(invoker, x, y);
}
}
使用table.setComponentPopupMenu(...) 向您的表注册您的ExtJPopupMenu 实例。