I've a GWT's ListBox with items:
listBox = new ListBox();
listBox.addItem("A");
listBox.addItem("B");
listBox.addItem("C");
and I would like it to be initialy unselected - so that no item is picked. The initial lack of selection should be symbolized by empty text and after selecting any item the user can't pick the "no selection item".
Unfortunately the following line:
listBox.setSelectedIndex(-1);
throws IndexOutOfBoundsException
.
Is it possible to obtain such behaviour with GWT ListBox?
Yes it's normal situation because when you call setSelectedIndex()
it will check the index whether is in the range. There is method in ListBox class.
private void checkIndex(int index) {
if (index < 0 || index >= getItemCount()) {
throw new IndexOutOfBoundsException();
}
}
So by default 0 index will be selected. If you want to add an empty text item for the first item, add an additional item for zero-index with an empty string:
listBox = new ListBox();
listBox.addItem(" ");
listBox.addItem("A");
listBox.addItem("B");
listBox.addItem("C");
listBox.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent changeEvent) {
SelectElement selectElement = listBox.getElement().cast();
selectElement.getOptions().getItem(0).setDisabled(true);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With