Skip to content

Instantly share code, notes, and snippets.

@lplotni
Created March 18, 2010 11:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lplotni/336275 to your computer and use it in GitHub Desktop.
Save lplotni/336275 to your computer and use it in GitHub Desktop.
A GWT ListBox widget implementing the HasValue<T> interface
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());
}
}
@paulord
Copy link

paulord commented Jun 29, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment