Created
March 18, 2010 11:43
-
-
Save lplotni/336275 to your computer and use it in GitHub Desktop.
A GWT ListBox widget implementing the HasValue<T> interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gwt.event.dom.client.ChangeEvent; | |
import com.google.gwt.event.dom.client.ChangeHandler; | |
import com.google.gwt.event.logical.shared.ValueChangeEvent; | |
import com.google.gwt.event.logical.shared.ValueChangeHandler; | |
import com.google.gwt.event.shared.HandlerRegistration; | |
import com.google.gwt.user.client.ui.HasValue; | |
import com.google.gwt.user.client.ui.ListBox; | |
/** | |
* A ListBox implementation supporting the HasValue interface. | |
* | |
* @author Lukasz Plotnicki <lukasz.plotnicki@med.uni-heidelberg.de> | |
* | |
*/ | |
public class ValueListBox extends ListBox implements HasValue<String> { | |
/** | |
* Flag indicating if the handler have been already initialized or not | |
*/ | |
private boolean valueChangeHandlerInitialized; | |
/* | |
* (non-Javadoc) | |
* | |
* @see com.google.gwt.user.client.ui.HasValue#getValue() | |
*/ | |
@Override | |
public String getValue() { | |
return getItemText(getSelectedIndex()); | |
} | |
/* | |
* (non-Javadoc) | |
* | |
* @see com.google.gwt.user.client.ui.HasValue#setValue(java.lang.Object) | |
*/ | |
@Override | |
public void setValue(String value) { | |
for (int i = 0; i < getItemCount(); i++) { | |
if (getItemText(i).equals(value)) { | |
setSelectedIndex(i); | |
break; | |
} | |
} | |
} | |
/* | |
* (non-Javadoc) | |
* | |
* @see com.google.gwt.user.client.ui.HasValue#setValue(java.lang.Object, | |
* boolean) | |
*/ | |
@Override | |
public void setValue(String value, boolean arg1) { | |
setValue(value); | |
if (arg1) | |
ValueChangeEvent.fire(this, value); | |
} | |
/* | |
* (non-Javadoc) | |
* | |
* @seecom.google.gwt.event.logical.shared.HasValueChangeHandlers# | |
* addValueChangeHandler | |
* (com.google.gwt.event.logical.shared.ValueChangeHandler) | |
*/ | |
@Override | |
public HandlerRegistration addValueChangeHandler( | |
ValueChangeHandler<String> handler) { | |
// Initialization code | |
if (!valueChangeHandlerInitialized) { | |
valueChangeHandlerInitialized = true; | |
addChangeHandler(new ChangeHandler() { | |
public void onChange(ChangeEvent event) { | |
ValueChangeEvent.fire(ValueListBox.this, getValue()); | |
} | |
}); | |
} | |
return addHandler(handler, ValueChangeEvent.getType()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this!
An observation: wouldn't it be more correct when getting a value to use the underlying ListBox.getValue(int) instead of getText() (which returns the item "caption" in the list box as opposed to its value) ? Same goes for setValue.