private <O> void addOptionsAndSetIfNull(final IsListBox source, final List<O> options, final ListBoxAdaptor<P, O> adaptor) { int i = 0; for (final O option : options) { source.addItem(adaptor.toDisplay(option), Integer.toString(i++)); } setToFirstIfNull(options, adaptor); for (int j = 0; j < options.size(); j++) { boolean contains = p.get().contains(adaptor.toValue(options.get(j))); source.setItemSelected(j, contains); } }
/** Binds our {@code p} to the selection in {@code source}, given the {@code options}. */ public <O> void toMultiple(final IsListBox source, final List<O> options, final ListBoxAdaptor<P, O> adaptor) { source.setMultipleSelect(true); addOptionsAndSetIfNull(source, options, adaptor); b.add(source.addChangeHandler(e -> { if (!active[0]) { active[0] = true; // collect all currently-selected options List<P> newOptions = new ArrayList<P>(); for (int i = 0; i < source.getItemCount(); i++) { if (source.isItemSelected(i)) { newOptions.add(adaptor.toValue(options.get(i))); } } p.set(newOptions); active[0] = false; } })); b.add(p.addPropertyChangedHandler(e -> { if (!active[0]) { active[0] = true; setToFirstIfNull(options, adaptor); for (int i = 0; i < options.size(); i++) { boolean contains = p.get().contains(adaptor.toValue(options.get(i))); source.setItemSelected(i, contains); } active[0] = false; } })); }