Search code examples
javaswingmouselistenerjpopupmenu

Add actions to JPopupMenu options


I have a class that extends JPanel and implements MouseListener. In this class, if the panel is clicked the following two functions are executed:

@Override
public void mouseClicked(MouseEvent e) {
    displayExitPopup();
}

private void displayExitPopup() {
    JPopupMenu exitPopup = new JPopupMenu();
    exitPopup.add("Exit Game");
    exitPopup.add("Cancel");
    exitPopup.show(this, this.getWidth(), this.getHeight());
}

This all works fine and the popup displays the 2 options as it should.

Now I am trying to perform actions when either of the two options in the popup menu are clicked - System.exit(0) if Exit Game is clicked, and the popup menu to close if Cancel is clicked. How can this be done?


Solution

  • If you take a look at the JavaDocs for JPopupMenu#add(String), you will find that it's a convenience method which returns a JMenuItem, you should then be able to add an ActionListener to it

    Take a look at Bringing up a PopupMenu for more details

    Having said that, I would instead, encourage you to make use the Action API which will allow you to create self contained units of work, which also provide the information needed to create the JMenuItem used by the JPopupMenu

    Have a look at How to Use Actions for more details

    You should also be using JComponent#setComponentPopupMenu instead of trying to use a MouseListener, as different platforms have different triggers for a popup menu and it's complicated and ugly real quick