我正在研究vaadin,我需要从菜单栏中选择的值并在标签中显示。我尝试了一个我在下面提到的示例代码。
final MenuBar menubar = new MenuBar();
layout.addComponent(menubar);
MenuBar.MenuItem beverages = menubar.addItem("Beverages", null, null);
Label selection = new Label("-");
layout.addComponent(selection);
MenuBar.Command mycommand = new MenuBar.Command() {
public void menuSelected(MenuItem selectedItem) {
selection.setValue("Ordered a " + selectedItem.getText() +
" from menu.");
}
};
MenuBar.MenuItem hot_beverages = beverages.addItem("Hot", null, null);
hot_beverages.addItem("Tea", null, mycommand);
hot_beverages.addItem("Coffee", null, mycommand);
MenuBar.MenuItem cold_beverages =
beverages.addItem("Cold", null, null);
cold_beverages.addItem("Milk", null, mycommand);
MenuBar.MenuItem snacks = menubar.addItem("Snacks", null, null);
snacks.addItem("Weisswurst", null, mycommand);
snacks.addItem("Salami", null, mycommand);
MenuBar.MenuItem services = menubar.addItem("Services", null, null);
services.addItem("Car Service", null, mycommand);
setContent(layout);
问题是,它只显示一个选定的项目。
如果我选择其他项目,则标签值将被最近选择的项目替换。我的要求是显示所有选定的菜单项。
答案 0 :(得分:0)
这取决于你真正需要做什么,但对于初学者你必须做两件事:
item.getParent().getChildren()
之类的操作并检查选中的子项<强>代码:强>
public class MultiSelectionMenu extends VerticalLayout {
public MultiSelectionMenu() {
final MenuBar menubar = new MenuBar();
MenuBar.MenuItem beverages = menubar.addItem("Beverages", null, null);
Label selection = new Label("-");
addComponent(selection);
MenuBar.Command selectionHandler = new MenuBar.Command() {
private List<String> selectedItems = new ArrayList<>();
public void menuSelected(MenuBar.MenuItem item) {
if (item.isChecked()) {
selectedItems.add(item.getText());
} else {
selectedItems.remove(item.getText());
}
selection.setValue("Ordered: " + Arrays.toString(selectedItems.toArray()));
}
};
MenuBar.MenuItem hot_beverages = beverages.addItem("Hot", null, null);
hot_beverages.addItem("Tea", null, selectionHandler).setCheckable(true);
hot_beverages.addItem("Coffee", null, selectionHandler).setCheckable(true);
MenuBar.MenuItem cold_beverages = beverages.addItem("Cold", null, null);
cold_beverages.addItem("Milk", null, selectionHandler).setCheckable(true);
MenuBar.MenuItem snacks = menubar.addItem("Snacks", null, null);
snacks.addItem("Weisswurst", null, selectionHandler).setCheckable(true);
snacks.addItem("Salami", null, selectionHandler).setCheckable(true);
MenuBar.MenuItem services = menubar.addItem("Services", null, null);
services.addItem("Car Service", null, selectionHandler).setCheckable(true);
addComponent(menubar);
}
}