import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;
public class Main extends JFrame{
public Main() {
setTitle("菜单");
setBounds(100, 200, 500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
Container c = getContentPane();
//创建菜单栏
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);//给窗体添加菜单栏
JMenu menu1 = new JMenu("文件F");
menu1.setMnemonic(KeyEvent.VK_F);//添加快捷键(alt+f)
menuBar.add(menu1);
JMenuItem newMenu = new JMenuItem("新建");
newMenu.addActionListener(new ItemListenner());//监听事件
menu1.add(newMenu);
JMenu openMenu = new JMenu("打开(K)");
openMenu.setMnemonic(KeyEvent.VK_K);//输入法英文,再打k
menu1.add(openMenu);
JMenuItem opennewMenu = new JMenuItem("打开新文件");
JMenuItem openoldMenu = new JMenuItem("打开旧文件");
openoldMenu.setEnabled(false);//菜单项禁用(默认为启用状态)
//不弹出菜单的情况下,可以启动加速器快捷键ctrl+alt+b
opennewMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B,KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK));
opennewMenu.addActionListener(new ItemListenner());
openMenu.add(opennewMenu);
openMenu.add(openoldMenu);
menu1.addSeparator();//添加分隔符
JMenuItem saveMenu = new JMenuItem("保存");
menu1.add(saveMenu);
JMenuItem exitMenu = new JMenuItem("退出");
menu1.add(exitMenu);
ImageIcon icon = new ImageIcon("src/tab.JPG");
newMenu.setIcon(icon);
//弹出式菜单
JPopupMenu popup = new JPopupMenu();
JMenuItem cutItem = new JMenuItem("剪切");
popup.add(cutItem);
cutItem.addActionListener(new ItemListenner());
JMenuItem copyItem = new JMenuItem("复制");
popup.add(copyItem);
copyItem.addActionListener(new ItemListenner());
JMenu editMenu = new JMenu("编辑");
popup.add(editMenu);
JMenu fontMenu = new JMenu("字体");
editMenu.add(fontMenu);
JMenuItem boldItem = new JMenuItem("加粗");
JMenuItem italicItem = new JMenuItem("斜体");
fontMenu.add(boldItem);
fontMenu.add(italicItem);
c.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {//鼠标按键释放触发此方法
if(e.isPopupTrigger()) {//判断此次事件是否为组件弹出的菜单事件
popup.show(e.getComponent(),e.getX(),e.getY());
}
}
});
}
private class ItemListenner implements ActionListener{//设置动作监听
@Override
public void actionPerformed(ActionEvent var1) {
JMenuItem item = (JMenuItem) var1.getSource();
System.out.println("你点击的是: "+item.getText());
}
}
public static void main(String args[]) {
new Main();
}
}
运行结果(运行结果都设有监听事件)
右键单击: