Vaadin Web应用开发教程(20):UI组件-MenuBar组件

jerry VaadinWeb 2015年11月25日 收藏

MenuBar 用来创建下拉菜单,类似桌面应用的菜单显示。
使用MenuBar首先创建MenuBar的实例:

  1. // Create a menu bar
  2. final MenuBar menubar = new MenuBar();
  3. main.addComponent(menubar);

然后通过addItem 为最上一级菜单添加菜单项,addItem 参数为String,一个图标资源,一个Command 对象(用户点击菜单项后所执行命令)。 icon 和command 可以为空。
Command对象为实现了MenuBar.Command 接口的对象,如:

  1. // A feedback component
  2. final Label selection = new Label("-");
  3. main.addComponent(selection);
  4.  
  5. // Define a common menu command for all the menu items.
  6. MenuBar.Command mycommand = new MenuBar.Command() {
  7. public void menuSelected(MenuItem selectedItem) {
  8. selection.setValue("Ordered a " +
  9. selectedItem.getText() +
  10. " from menu.");
  11. }
  12. };
  13.  

addItem() 方法返回一个MenuBar.MenuItem 对象,利用这个返回值,你可以参加子菜单。MenuItem 也有同样的addItem 方法。

  1. // Put some items in the menu hierarchically
  2. MenuBar.MenuItem beverages =
  3. menubar.addItem("Beverages", null, null);
  4. MenuBar.MenuItem hot_beverages =
  5. beverages.addItem("Hot", null, null);
  6. hot_beverages.addItem("Tea", null, mycommand);
  7. hot_beverages.addItem("Coffee", null, mycommand);
  8. MenuBar.MenuItem cold_beverages =
  9. beverages.addItem("Cold", null, null);
  10. cold_beverages.addItem("Milk", null, mycommand);
  11.  
  12. // Another top-level item
  13. MenuBar.MenuItem snacks =
  14. menubar.addItem("Snacks", null, null);
  15. snacks.addItem("Weisswurst", null, mycommand);
  16. snacks.addItem("Salami", null, mycommand);
  17.  
  18. // Yet another top-level item
  19. MenuBar.MenuItem services =
  20. menubar.addItem("Services", null, null);
  21. services.addItem("Car Service", null, mycommand);
  22.  

显示结果如下: