Search code examples
javaswingmouseeventjmenuitemjpopupmenu

JPopupMenu not showing text of JMenuItem


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?


Solution

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