tags:

views:

195

answers:

2

My code is

          VerticalPanel v1 = new VerticalPanel();

 Command comm = new Command() {
  @Override
  public void execute() {
                       // How i know that which menu item is cliked
  }
 };

 MenuBar menu = new MenuBar();
 menu.setWidth("500px");
 menu.setAnimationEnabled(true);
 menu.setAutoOpen(true);
 menu.addSeparator();
 MenuBar fileBar = new MenuBar(true);
 MenuBar editBar = new MenuBar(true);

 fileBar.addItem(new MenuItem("New", comm));
 fileBar.addSeparator();
 fileBar.addItem(new MenuItem("Open", comm));
 fileBar.addItem(new MenuItem("Save", comm));

 editBar.addItem("Edit 11", comm);
 editBar.addItem("Edit 11", comm);

 menu.addItem(new MenuItem("File", fileBar));
 menu.addItem(new MenuItem("Edit", editBar));

 v1.add(menu);

please help me

+1  A: 

I get answer

 Command comm1 = new Command() {
  @Override
  public void execute() {
   Window.alert("New item is clicked");
  }
 };

 Command comm2 = new Command() {
  @Override
  public void execute() {
   Window.alert("Open item is clicked");
  }
 };

                fileBar.addItem(new MenuItem("New", comm1));

                fileBar.addItem(new MenuItem("Open", comm2));

but we have to create separate object for that ...

but i don't think that this is perfect solution , but it work 100%

Tushar Ahirrao
A: 

I doesn't seem to be something you get out of the box. But you can use on of the following options:

  1. In MenuBar there is a protected method getSelectedItem(), this returns the MenuItem which should match the one clicked. I don't know why it's protected, but by extending the MenuBar class and make it public you should be able to use it.

  2. You can create a Command class, where you inject the MenuItem upon creation, in that case you need to set the command after creation and not in the constructor of the MenuItem

Command implementation:

public class MyCommand implements Command {

  private final MenuItem item;

  public MyCommand(MenuItem item) {
    this.item = item;
  }

  @Override
  public void execute() {
    //item matches the item clicked.
  }
}

Usage:

MenuItem newItem = new MenuItem("New", (Command)null);
newItem.setCommand(new MyCommand(newItem));

Or instead of passing the MenuItem via the MyCommand constructor add a method to the MyCommand class named setMenuItem:

MenuItem newItem = new MenuItem("New", new MyCommand());
((MyCommand)newItem.getCommand()).setMenuItem(newItem);
Hilbrand
Thanks dude it works
Tushar Ahirrao