如何通过右键单击选择列表/树/表项并同时打开上下文菜单?

huangapple go评论58阅读模式
英文:

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(...) 方法,像这样(适用于 JTableJListJTree 的示例工作方式类似):

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(...).

huangapple
  • 本文由 发表于 2020年8月4日 17:26:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63243889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定