在MacOS上的软件都有一个菜单栏,会浮现在屏幕顶部,Java的awt包中也提供了构建菜单功能的相关组件,示例代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| static void MenuTest(){ Frame frame = new Frame("Menu"); MenuBar menuBar = new MenuBar(); frame.setMenuBar(menuBar); Menu m1 = new Menu("文件", true); menuBar.add(m1); MenuItem menuItem1 = new MenuItem("新建"); MenuItem menuItem2 = new MenuItem("打开"); m1.add(menuItem1); m1.add(menuItem2); Menu m2 = new Menu("编辑", true); menuBar.add(m2); MenuItem menuItem3 = new MenuItem("复制"); MenuItem menuItem4 = new MenuItem("粘贴"); m2.add(menuItem3); m2.add(menuItem4); Menu m3 = new Menu("帮助", true); menuBar.setHelpMenu(m3); MenuItem menuItem5 = new MenuItem("问询"); MenuItem menuItem6 = new MenuItem("联系我们"); m3.add(menuItem5); m3.add(menuItem6); frame.pack(); frame.show(); }
|
效果如下:
MenuBar用来创建菜单栏,其中常用方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public MenuBar();
public Menu getHelpMenu();
public void setHelpMenu(Menu m);
public Menu add(Menu m);
public void remove(int index);
public void remove(MenuComponent m);
public int getMenuCount();
public int countMenus();
public Menu getMenu(int i);
|
Menu类为菜单对象,其中可以添加选项类MenuItem对象,Menu类中常用方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public Menu();
public Menu(String label);
public Menu(String label, boolean tearOff);
public boolean isTearOff();
public int getItemCount();
public int countItems();
public MenuItem getItem(int index);
public MenuItem add(MenuItem mi);
public void add(String label);
public void insert(MenuItem menuitem, int index);
public void insert(String label, int index) ;
public void addSeparator();
public void insertSeparator(int index);
public void remove(int index);
public void remove(MenuComponent item);
public void removeAll() ;
|
下面是MenuItem类的方法解析:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public MenuItem();
public MenuItem(String label);
public MenuItem(String label, MenuShortcut s);
public String getLabel() ;
public synchronized void setLabel(String label);
public boolean isEnabled();
public synchronized void setEnabled(boolean b);
public MenuShortcut getShortcut();
public void setShortcut(MenuShortcut s);
public void deleteShortcut();
public synchronized void addActionListener(ActionListener l);
public synchronized void removeActionListener(ActionListener l);
public synchronized ActionListener[] getActionListeners();
|