How to add a keystroke to a Java Swing application

If you ever need to add a keystroke to a Java Swing application (or Scala Swing), this code may help. It shows how to add the [Command][M] keystroke on a Mac OS X system to a Swing application. It makes the keystroke available in a “Window” menu:

// (1) init
JMenuBar menuBar = new JMenuBar();
JMenu windowMenu = new JMenu();
JMenuItem minimizeWindowMenuItem = new JMenuItem();
 
// (2) in the constructor
windowMenu.setText("Window");
minimizeWindowMenuItem.setText("Minimize Window");
minimizeWindowMenuItem.addActionListener(new ActionListener()
{
  public void actionPerformed(final ActionEvent e)
  {
     minimizeWindowMenuItem_actionPerformed(e);
   }
});
minimizeWindowMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M,  Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
  
// (3) some time later
windowMenu.add(minimizeWindowMenuItem);
 
menuBar.add(windowMenu);
this.setJMenuBar(menuBar);

// (4)
public void minimizeWindowMenuItem_actionPerformed(final ActionEvent e) {
  mainFrame.setExtendedState(Frame.ICONIFIED);
}

I’m not going to add anything else here, but as mentioned, if you want to add a keystroke to a Java Swing application, I believe this is the correct approach, especially if you want the keystroke to appear as a menu item in a menu.