Catching the event when a JMenuItem has been selected

Add an ActionListener object. Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("menu");
      JMenuItem menuItem1 = new JMenuItem("option 1");
      JMenuItem menuItem2 = new JMenuItem("option 2");
      JMenuItem menuItem3 = new JMenuItem("option 3");
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
      menuItem3.addActionListener(this);
      menu.add(menuItem1);
      menu.add(menuItem2);
      menu.add(new JSeparator());
      menu.add(menuItem3);
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }

   public void actionPerformed(ActionEvent ae) {
      System.out.println(ae.getActionCommand() + " selected!");
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}