0

I'm trying to create a JPopupMenu, but for some reason, it doesn't show the text I've set on the JMenuItems. The menu itself works, there are menuitems in it and they are responsive, but the text is not showing. I'm creating the menu like this:

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);      
}

In case it matters, here is the 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());
        }
    }
}

What am I missing here?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Tobi
  • 5,499
  • 3
  • 31
  • 47

2 Answers2

3

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

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

The setAction(...) method reset the properties of the menu item with the properties of the Action. So you need to make sure you set the NAME property of the Action to set the text of the menu item.

So in your case it looks like the value of the NAME property should be:

SketchPad.ADD_PLACE_POPUP_TEXT

Or the other approach is to reset the text of the menu item after you set the Action

JMenuItem addPlaceMenuItem = new JMenuItem( new PopupAction(ActionType.AddPlace) );
addPlaceMenuItem.setText(SketchPad.ADD_PLACE_POPUP_TEXT);
camickr
  • 321,443
  • 19
  • 166
  • 288
2

The effect is platform specific. In particular, "In Microsoft Windows, the user by convention brings up a popup menu by 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 in order to handle multiple selection and a context menu.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045