How do i know that which menu item is clicked?
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:
In
MenuBar
there is a protected methodgetSelectedItem()
, this returns theMenuItem
which should match the one clicked. I don't know why it's protected, but by extending theMenuBar
class and make it public you should be able to use it.You can create a
Command
class, where you inject theMenuItem
upon creation, in that case you need to set the command after creation and not in the constructor of theMenuItem
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%
精彩评论