Java为菜单栏添加快捷键
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);
}
}
}