英文:
How can I select a list/tree/table item via right-click and open a context menu at the same time?
问题
当我在Swing表格/树形/列表中的项目上进行右键单击时,
- 应当选中该项目,且
- 应当显示适当的JPopupMenu(上下文菜单)。
我该如何实现这一功能?
我正在使用 component.setComponentPopupMenu(popupMenu)
为我的组件注册弹出菜单,但似乎这会吞噬右键单击事件,从而无法选中目标项目。
英文:
When I right-click on an item in a Swing table/tree/list,
- the item should be selected and
- an appropriate JPopupMenu (context menu) should be shown.
How can I achieve this?
I'm using component.setComponentPopupMenu(popupMenu)
to register popup menus for my components, which seems to swallow the right-click event so that the targeted item is never selected.
答案1
得分: 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);
}
}
// 确保新选择的项获得焦点
invoker.requestFocus();
// 现在为所选项构建适当的菜单
[...]
// 最后显示菜单
super.show(invoker, x, y);
}
}
使用 table.setComponentPopupMenu(...)
注册您的 ExtJPopupMenu
实例到您的表格中。
英文:
The issue here is that the right-click is indeed consumed by the built-in popup trigger.
To work around this, override the JPopupMenu.show(...)
method like this (sample for JTable
, JList
and JTree
work similarly):
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);
}
}
Register your ExtJPopupMenu
instance with your table using table.setComponentPopupMenu(...)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论