JPopupMenu 不显示 JMenuItem 的文本

JPopupMenu not showing text of JMenuItem

我试图创建一个JPopupMenu,但是由于某种原因,它没有显示我在JMenuItems上设置的文本。菜单本身有效,其中有benuitems,它们反应灵敏,但文本没有显示。我正在创建这样的菜单:

private void createPopupMenu() {
    this.popupMenu = new JPopupMenu();      
    this.addMouseListener(new PopupListener(this));
    JMenuItem addPlaceMenuItem = new JMenuItem(SketchPad.ADD_PLACE_POPUP_TEXT);
    addPlaceMenuItem.setAction(new PopupAction(ActionType.AddPlace));
    this.popupMenu.add(addPlaceMenuItem);
    JMenuItem addTransitionMenuItem = new JMenuItem(SketchPad.ADD_TRANSITION_POPUP_TEXT);
    addTransitionMenuItem.setAction(new PopupAction(ActionType.AddTransition));
    this.popupMenu.add(addTransitionMenuItem);      
}

如果很重要,这是PopupListener

class PopupListener extends MouseAdapter {

    SketchPad pad;

    public PopupListener(SketchPad pad)
    {
        this.pad = pad;
    }

    public void mousePressed(MouseEvent e) {
        maybeShowPopup(e);
    }

    public void mouseReleased(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON1)
        {
            this.pad.getController().deselectAllNodes();
        }
        else
        {
            maybeShowPopup(e);
        }
    }

    private void maybeShowPopup(MouseEvent e) {
        if (e.isPopupTrigger()) {               
            pad.popupPosition = new Point(e.getX(), e.getY());
            pad.popupMenu.show(e.getComponent(), e.getX(), e.getY());
        }
    }
}

我在这里错过了什么?

but for some reason, it doesn't show the text I've set on the JMenuItems.

addPlaceMenuItem.setAction(new PopupAction(ActionType.AddPlace));

setAction(...) 方法使用 Action 的属性重置菜单项的属性。所以你需要确定你设置了ActionNAME属性来设置菜单项的文本。

所以在你的例子中,NAME 属性 的值看起来应该是:

SketchPad.ADD_PLACE_POPUP_TEXT

或者另一种方法是在设置操作后重置菜单项的文本

JMenuItem addPlaceMenuItem = new JMenuItem( new PopupAction(ActionType.AddPlace) );
addPlaceMenuItem.setText(SketchPad.ADD_PLACE_POPUP_TEXT);

效果因平台而异。特别是,“在 Microsoft Windows 中,用户按照惯例 releasing the right mouse button while the cursor is over a component that is popup-enabled." Your implementation of mouseReleased() precludes even checking isPopupTrigger(). Instead, handle the selection and check the trigger. A similar approach is shown in GraphPanel 会弹出一个弹出菜单,以便处理多重选择和上下文菜单。