Disable the keyboard accellerator that has been assigned to a JMenuItem

Set the accelerator to null. This example assigns accelerators to the JMenuItems ‘male’ and ‘female’. Press CTRL-M and CTRL-F to invoke them. After 5 selections, the accelerators will be disabled.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   JMenuItem menuItem1;
   JMenuItem menuItem2;
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Sex");
      menuItem1 = new JMenuItem("male");
      menuItem2 = new JMenuItem("female");
 
      // add the MenuItems to the Menu 
      menu.add(menuItem1);
      menu.add(menuItem2);
      menuItem1.setAccelerator(KeyStroke.getKeyStroke('M', Event.CTRL_MASK));
      menuItem2.setAccelerator(KeyStroke.getKeyStroke('F', Event.CTRL_MASK));
 
      // listen for events on these MenuItems
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
 
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   private int count = 0;
   public void actionPerformed(ActionEvent ae) {
      System.out.println(ae.getActionCommand());
 
      count++;
      if (count == 5) {
         System.out.println("now disabling accelerators");
 
         menuItem1.setAccelerator(null);
         menuItem2.setAccelerator(null);
      }
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}