Programmatically unchecking a Checkbox within Vaadin Context Menu

Viewed 189

I've created a Context menu with a tree structure (added Menu items, then added Checkboxes within those menu items as sub-menu items). This works just fine in terms of adding/removing items manually. However, when it comes to programmatically resetting items there is a conflict in terms of a general Component vs. specific component (in this case, a Checkbox).

Component comp = contextMenu.getItems().get(x).getSubMenu().getItems().get(y);
if (comp instanceof Checkbox) {
    ((Checkbox) comp).setValue(false);
}

Note that comp is not in fact an instance of Checkbox; rather it is returning as com.vaadin.flow.component.contextmenu.MenuItem and that item cannot be cast to a Checkbox. So the question is, how would I uncheck a given Checkbox?

1 Answers

What Hawk said:

If you've created the menu item something like menuItem.getSubMenu().addItem(new Checkbox("My option")), then you can iterate through the child components and deselect them:

menuItem.getSubMenu().getItems().forEach(subMenuItem -> {
  subMenuItem.getChildren()
      .filter(Checkbox.class::isInstance)
      .map(Checkbox.class::cast)
      .forEach(c -> c.setValue(false));
});

But another approach is to make the items selectable with setCheckable(true). Then you would deselect them as such:

menuItem.getSubMenu().getItems().forEach(subMenuItem -> subMenuItem.setChecked(false));

There are two downsides that come to mind when using setCheckable(true). First, a checkable item can not have submenus. Second, the menu will close when an item is checked.

Related