开发者

How do i know that which menu item is clicked?

开发者 https://www.devze.com 2022-12-09 05:08 出处:网络
My code is VerticalPanel v1 = new VerticalPanel(); Command comm = new Command() { @Override public void execute() {

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.addSep开发者_如何学Goarator();
    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


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);


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%

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号