KBEC-00202 - ListBox usage examples

Article ID:360032829852
1 minute readKnowledge base
On this page

Summary

ListBox is a class provided by GWT. This article provides examples for using a ListBox.

Solution

See examples below.

Examples

Create a ListBox, make it visible but greyed out

final ListBox listBox = new ListBox();
listBox.addItem("Item1","Item1 Value");
listBox.addItem("Item 2", "Item2 Value");

// This should make the ListBox visible but greyed out
listBox.setEnabled(false);

Get the value of the item the user has selected in the drop down list

VerticalPanel verticalPanel = new VerticalPanel();

final ListBox listBox = new ListBox();
listBox.addItem("Item1","Item1 Value");
listBox.addItem("Item 2", "Item2 Value");

verticalPanel.add(listBox);

Button demoButton1 = new Button("Get the Value of the ListBox");

demoButton1.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
// Example of how to get the selected item's value
        Window.alert("Value of ListBox: " + listBox.getValue(listBox.getSelectedIndex()));
    }
});

Set an empty value and make it appear as the first item and make it auto select

final ListBox listBox = new ListBox();
// Set the empty value
listBox.addItem("", "");
listBox.addItem("Item1","Item1 Value");
listBox.addItem("Item 2", "Item2 Value");

verticalPanel.add(listBox);

Button demoButton1 = new Button("Get the Value of the ListBox");

demoButton1.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
        Window.alert("Value of ListBox: " + listBox.getValue(listBox.getSelectedIndex()));
    }
});

verticalPanel.add(demoButton1);