Java -- AWT 菜单建立, Menu, 右键菜单

1. Menu类结构

 

2. 菜单示例:  MenuBar容器中可以装Menu,Menu容器中可以装MenuItem。

public class SimpleMenu {

	Frame f = new Frame("test Menu");
	MenuBar mb = new MenuBar();
	Menu file = new Menu("File");
	Menu edit = new Menu("Edit");
	MenuItem newItem = new MenuItem("New");
	MenuItem saveItem = new MenuItem("Save");
	MenuItem exitItem = new MenuItem("Exit", new MenuShortcut(KeyEvent.VK_X));
	CheckboxMenuItem autoWrap = new CheckboxMenuItem("AutoWrap");
	MenuItem copyItem = new MenuItem("Copy");
	MenuItem pasteItem = new MenuItem("Paste");
	Menu format = new Menu("Format");
	MenuItem commentItem = new MenuItem("Comment", new MenuShortcut(KeyEvent.VK_SLASH,true));
	MenuItem cancelItem = new MenuItem("non-Comment");
	TextArea ta = new TextArea(6, 40);
	
	public void init()
	{
		ActionListener menuListener = new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				String cmd = arg0.getActionCommand();
				ta.append("Click" + cmd + "menu\n" );
				if( cmd.equals("cancel") )
				{
					System.exit(0);
				}
			}
		};
		
		commentItem.addActionListener(menuListener);
		exitItem.addActionListener(menuListener);
		file.add(newItem);
		file.add(saveItem);
		file.add(exitItem);
		edit.add(autoWrap);
		edit.addSeparator();
		edit.add(copyItem);
		edit.add(pasteItem);
		format.add(commentItem);
		format.add(cancelItem);
		edit.add(new MenuItem("-"));
		edit.add(format);
		mb.add(file);
		mb.add(edit);
		
		f.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e)
			{
				System.exit(0);
			}
		});
		f.setMenuBar(mb);
		f.add(ta);
		f.pack();
		f.setVisible(true);		
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("SimpleMenu");
		new SimpleMenu().init();
	}
}


添加右键菜单,上面的程序修改一下, 可以变换TextArea的右键菜单, 其他控件也可以用这种方法添加右键菜单。

	PopupMenu pop = new PopupMenu(); //右键菜单

		pop.add(autoWrap);
		pop.addSeparator();
		pop.add(copyItem);
		pop.add(pasteItem);
		ta.add(pop);
		ta.addMouseListener(new MouseAdapter() {   //鼠标事件监听
			public void mouseReleased(MouseEvent e)
			{
				if( e.isPopupTrigger() )
				{
					pop.show(ta, e.getX(), e.getY()); //显示右键菜单
				}				
			}					
		});		


 

 

posted @ 2013-11-01 16:41  今晚打酱油_  阅读(482)  评论(0编辑  收藏  举报