Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GWT ListBox unselected by default

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?

like image 820
rafalry Avatar asked Mar 02 '12 13:03

rafalry


1 Answers

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);

        }
    });
like image 105
Jama A. Avatar answered Sep 27 '22 02:09

Jama A.