menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,ActionEvent.ALT_MASK));
是当鼠标焦点在你所在的程序界面上,你按下ALT和D键就能打开相应的menuItem,而menuItem.setMnemonic(KeyEvent.VK_D)则是当你把焦点放在相应的menuItem上同时按下D键显示相应的menuItem


   
        JMenuItem mntmExchange = new JMenuItem("Exchange");
        //MenuShortcut shortcut=new MenuShortcut(KeyEvent.VK_Q);
        mntmExchange.setMnemonic(KeyEvent.VK_Q);
        mntmExchange.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D,ActionEvent.ALT_MASK));
       


ava为菜单栏添加快捷键

package swimg;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

public class JMenuDemo extends JMenuBar implements ActionListener{
JMenuItem item1;
public JMenuDemo(){
   add(createJMenuone());
 
}
public JMenu createJMenuone(){
   JMenu menu=new JMenu("文件(F)");
   menu.setMnemonic(KeyEvent.VK_F);
   JMenuItem item=new JMenuItem("新建(N)",KeyEvent.VK_N);
   item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK));
   menu.add(item);
   item1=new JMenuItem("退出(X)",KeyEvent.VK_X);
   item1.addActionListener((ActionListener) this);
   item1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,ActionEvent.CTRL_MASK));
   menu.add(item1);
   return menu;
}
public static void main(String[] args) {
   JFrame frame=new JFrame("菜单栏");
   frame.setBounds(200,200,400,400);
   frame.setResizable(true);
   frame.setJMenuBar(new JMenuDemo());
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setVisible(true);
 
}
public void actionPerformed(ActionEvent e) {
   // TODO 自动生成方法存根
   if(e.getSource()==item1){
      System.exit(0);
   }
}

}


Java 菜单快捷键_java