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); source.setSelectedIndex(indexInOptions(adaptor, options)); }
/** Binds our {@code p} to the selection in {@code source}, given the {@code options}. */ public <O> void to(final IsListBox source, final List<O> options, final ListBoxAdaptor<P, O> adaptor) { addOptionsAndSetIfNull(source, options, adaptor); b.add(source.addChangeHandler(e -> { final int i = source.getSelectedIndex(); // getSelectedIndex within an onchange should never be -1, but check just in case if (i != -1) { p.set(adaptor.toValue(options.get(i))); } })); b.add(p.addPropertyChangedHandler(e -> { setToFirstIfNull(options, adaptor); source.setSelectedIndex(indexInOptions(adaptor, options)); })); }
/** Binds our {@code p} to the selection in {@code source}, given the {@code options}. */ public <O> void to(final IsListBox source, final ListProperty<O> options, final ListBoxAdaptor<P, O> adaptor) { if (options.get() != null) { addOptionsAndSetIfNull(source, options.get(), adaptor); } b.add(source.addChangeHandler(e -> { final int i = source.getSelectedIndex(); // getSelectedIndex within an onchange should never be -1, but check just in case if (i != -1) { p.set(adaptor.toValue(options.get().get(i))); } })); b.add(p.addPropertyChangedHandler(e -> { setToFirstIfNull(options.get(), adaptor); source.setSelectedIndex(indexInOptions(adaptor, options.get())); })); options.addPropertyChangedHandler(e -> { // it looks like this does not cause an onchange in the browser source.clear(); if (options.get() != null) { addOptionsAndSetIfNull(source, options.get(), adaptor); // reselect the 1st value if p's current value is not available. if (p.get() != null && indexInOptions(adaptor, options.get()) == -1 && !options.get().isEmpty()) { p.setInitialValue(adaptor.toValue(options.get().get(0))); } } }); }