组合框自动完成

时间:2010-02-27 00:06:11

标签: gwt combobox

无论如何都要让组合框的自动完成从文本的任何地方开始,让我举个例子。如果我在组合框中有一个名叫约翰·史密斯的人,如果我从字母“j”开始,它会拉起约翰·史密斯,但更少说我想从字母's'开始搜索他的姓,那是否可能,如果是这样的话有没有人有代码或链接到代码执行此操作。

4 个答案:

答案 0 :(得分:12)

你看过SuggestBox了吗?将数据提供给建议框的MultiWordSuggestOracle似乎完全符合您的要求 - 请参阅javadocs了解用法和示例。

更新:这是一个很好的例子,可以自定义GWT SuggestBox看起来像Facebook上的那个:http://raibledesigns.com/rd/entry/creating_a_facebook_style_autocomplete请务必遵循该教程中的所有链接,如它们包含大量有关使用SuggestBox

的信息

答案 1 :(得分:3)

我对AdvancedComboBoxExample sencha有任何问题 http://www.sencha.com/examples/#ExamplePlace:advancedcombobox

我在此链接http://www.sencha.com/forum/showthread.php?222543-CRTL-C-triggers-a-reload-of-data-in-Combobox中找到了对我的问题的回复。

我必须对我的代码进行一些调整。以下是需要它的人的代码。

没有分页的ComboBox ajax:

import com.extjs.gxt.ui.client.data.*;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.List;
import java.util.Map;

public class AjaxComboBox<T extends ModelData> extends ComboBox<T> {

    public AjaxComboBox() {
    }

    public interface GetDataCallback<T> {

        void getData(String query, AsyncCallback<List<T>> dataCallback);
    }

    public AjaxComboBox(final String displayField, final int minChars, final GetDataCallback<T> getDataCallback) {
        final RpcProxy<ListLoadResult<T>> proxy = new RpcProxy<ListLoadResult<T>>() {

            @Override
            protected void load(final Object loadConfig, final AsyncCallback<ListLoadResult<T>> callback) {
                ListLoadConfig load = (ListLoadConfig) loadConfig;
                final Map<String, Object> properties = load.getProperties();

                getDataCallback.getData((String) properties.get("query"), new AsyncCallback<List<T>>() {

                    public void onFailure(Throwable caught) {
                        caught.printStackTrace();
                    }

                    public void onSuccess(List<T> result) {
                        callback.onSuccess(new BaseListLoadResult<T>(result));
                    }
                });

            }
        };
        final BaseListLoader<ListLoadResult<T>> loader = new BaseListLoader<ListLoadResult<T>>(proxy);
        final ListStore<T> store = new ListStore<T>(loader);
        setFieldLabel(displayField);
        setStore(store);
        setHideTrigger(true);
        setMinChars(minChars);
        setWidth(300);
    }

}

ComboBox懒惰与分页

import com.extjs.gxt.ui.client.data.*;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.Map;

public class ComboBoxLazy<T extends ModelData> extends ComboBox<T> {

    public interface GetPagingDataCallback<T> {

        void getData(String query, PagingLoadConfig loadConfig,
                AsyncCallback<PagingLoadResult<T>> dataCallback);
    }

    public ComboBoxLazy(final String displayField, final int minChars,
            final GetPagingDataCallback<T> getDataCallback) {


        final RpcProxy<PagingLoadResult<T>> proxy = new RpcProxy<PagingLoadResult<T>>() {

            @Override
            protected void load(Object loadConfig,
                    final AsyncCallback<PagingLoadResult<T>> callback) {
                final Map<String, Object> properties = ((PagingLoadConfig) loadConfig).getProperties();
                getDataCallback.getData((String) properties.get("query"),
                        ((PagingLoadConfig) loadConfig),
                        new AsyncCallback<PagingLoadResult<T>>() {

                            @Override
                            public void onSuccess(
                                    final PagingLoadResult<T> result) {
                                callback.onSuccess(result);
                            }

                            @Override
                            public void onFailure(Throwable caught) {
                                callback.onFailure(caught);
                            }
                        });
            }
        };


        ModelReader reader = new ModelReader();
        final BasePagingLoader<PagingLoadResult<T>> loader = new BasePagingLoader<PagingLoadResult<T>>(
                proxy, reader);
        loader.addListener(Loader.BeforeLoad, new Listener<LoadEvent>() {

            public void handleEvent(LoadEvent be) {
                be.<ModelData>getConfig().set("start",
                        be.<ModelData>getConfig().get("offset"));
            }
        });

        setFieldLabel(displayField);
        final ListStore<T> store = new ListStore<T>(loader);
        setStore(store);
        setHideTrigger(true);
        setMinChars(minChars);
        setPageSize(10);
        setWidth(300);
    }

}

班级考试

import br.ueg.escala.client.view.ConversorBeanModel;
import com.extjs.gxt.ui.client.data.*;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;

import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.List;
public class ComboBoxTest extends LayoutContainer {

   @Override
    protected void onRender(Element parent, int index) {
        super.onRender(parent, index);
        criarComboBox();
        criarComboBoxLazy();
    }

    private void criarComboBox() {

        final AjaxComboBox<BeanModel> combo = new AjaxComboBox<BeanModel>("name", 3, new AjaxComboBox.GetDataCallback<BeanModel>() {

            public void getData(String query, final AsyncCallback<List<BeanModel>> dataCallback) {
                servico.loadLike(query, new AsyncCallback<List<Person>>() {

                    public void onFailure(Throwable caught) {
                        caught.printStackTrace();
                    }

                    public void onSuccess(List<Person> result) {
                        List<BeanModel> dados = ConversorBeanModel.getListBeanModel(result);
                        dataCallback.onSuccess(dados);
                    }
                });
            }
        });

        combo.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {

            @Override
            public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
                BeanModel bm = combo.getView().getSelectionModel().getSelectedItem();
                Person p = bm.getBean();
                combo.setValue(bm);

                try {
                    combo.setValue(bm);
                    combo.setRawValue(p.getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        combo.setItemSelector("div.search-item");
        combo.setTemplate(getTemplate());

        addText("Any text");
        add(combo);
    }

    private void criarComboBoxLazy() {
        String field = "name";
        final ComboBoxLazy<BeanModel> comboLazy = new ComboBoxLazy<BeanModel>(field, 3, new                     ComboBoxLazy.GetPagingDataCallback<BeanModel>() {

            public void getData(String query, PagingLoadConfig loadConfig, final AsyncCallback<PagingLoadResult<BeanModel>> dataCallback) {
                final PagingLoadConfig load = (PagingLoadConfig) loadConfig;

                servico.loadLike(load, new Person(), "name", query, new AsyncCallback<List>() {

                    public void onFailure(Throwable caught) {
                        caught.printStackTrace();
                    }

                    public void onSuccess(List result) {
                        PagingLoadResult<BeanModel> dados = ConversorBeanModel.getPagingLoadResultBeanModel(result, load);
                        dataCallback.onSuccess(dados);
                    }
                });
            }
        });

        comboLazy.addSelectionChangedListener(new SelectionChangedListener<BeanModel>() {

            @Override
            public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
                BeanModel bm = comboLazy.getView().getSelectionModel().getSelectedItem();
                Person p = bm.getBean();
                comboLazy.setValue(bm);

                try {
                    comboLazy.setValue(bm);
                    comboLazy.setRawValue(p.getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        comboLazy.setItemSelector("div.search-item");
        comboLazy.setTemplate(getTemplate());

        VerticalPanel vp2 = new VerticalPanel();
        vp2.setSpacing(10);
        vp2.addText("<span class='text'><b>Combo lazy</span>");
        vp2.add(comboLazy);
        add(vp2);
    }

    private native String getTemplate() /*-{
    return [ '<tpl for="."><div class="search-item">',
    ' <h3> <span> Name:</span> <span style="font-weight:normal;">{name}</span> ',
    ' <span> - Last name:</span> <span style="font-weight: normal">{lastName}</span></h3>', '</div></tpl>'].join("");
    }-*/;

}

Application.css:

.searchItem {
  font: normal 11px tahoma, arial, helvetica, sans-serif;
  padding: 3px 10px 3px 10px;
  white-space: normal;
  color: #555;
}

.searchItem h3 {
  display: block;
  font: inherit;
  font-weight: bold;
  color: #222;
}

.searchItem h3 span {
  float: right;
  font-weight: normal;
  margin: 0 0 5px 5px;
  width: 100px;
  display: block;
  clear: none;
}

代码服务器

public List loadLike(PagingLoadConfig config, Person classe, String field, String query) {
    List<Person> list = null;
    try {
        List listEntity = genericoBC.loadLike(config.getOffset(), config.getLimit(), field, query, classe.getClass());
        list = clone(listEntity);

        final int totalCount = genericoBC.contarRegistros(classe.getClass());
        config.setLimit(totalCount);
    } catch (Exception e) {
        tratarExcecao("", e);
    }
    return list;
}

public List<Person> loadLike(String query) {
    List<Person> list = null;
    try {
        List<Person> listEntity = genericoBC.loadLike(query);
        list = clone(listEntity);
    } catch (Exception e) {
        tratarExcecao("Error:genericoBC.loadLike(query)", e);
    }
    return list;
}

答案 2 :(得分:2)

覆盖组合框的 ListStore 的方法 boolean isFiltered(ModelData record,String property)。方法体将如下:

if (filterBeginsWith != null && property != null) {
    Object o = record.get(property);
    if (o != null) {
        if (!o.toString().toLowerCase().contains(filterBeginsWith.toLowerCase())) {
            return true;
        }
    }
}
if (filters != null) {
    for (StoreFilter filter : filters) {
        boolean result = filter.select(this, record, record, property);
        if (!result) {
            return true;
        }
    }
}
return false;

答案 3 :(得分:0)

这适用于GXT 3.0。

首先,创建一个被覆盖的ListStore类的实例,如下所示:

  public static class MyListStore extends ListStore<Course>{
  private String userText="";
  public MyListStore(ModelKeyProvider<Course> k){ 
    super(k); 
  }

  @Override
  protected boolean isFilteredOut(Course item) {
    boolean result = false;
    if(item.getTitle()!=null && 
      !item.getTitle().toUpperCase().contains(userText.toUpperCase())){
      result = true;
    }
    return result;
  }
  public void setUserText(String t){ userText = t; }
}

在这种情况下,我有一个课程模型类,其中包含课程标题(一个字符串)作为组合框的标签提供者。因此,在您重写的类中,执行类似的操作:使用您的特定模型(此组合框实例的类型)代替上面代码中的“课程”。

接下来,创建此商店的实例以供组合框使用:

  private MyListStore courses ;

接下来,请确保使用此方法适当地初始化组合框。在我的情况下,我使用uibinder,所以我的初始化程序是这样的:

  @UiFactory
  ListStore<Course> createListStore() {
    courses = new MyListStore(courseProps.key());
    return courses;
  }

相关的uibinder片段:

  <ui:with type="com.sencha.gxt.data.shared.LabelProvider" field="titles"/>
  <ui:with type="com.sencha.gxt.data.shared.ListStore" field="courses"/>
  ...
  <form:ComboBox ui:field="classTitle" store="{courses}" labelProvider="{titles}"
        allowBlank="false" forceSelection="true" triggerAction="ALL" width="200" />

当然,链接到绑定的java类:

  @UiField ComboBox<Course> classTitle;

最后,确保从组合框输入中处理keyup事件:

classTitle.addKeyUpHandler(new KeyUpHandler(){
  @Override
  public void onKeyUp(KeyUpEvent event) {
    courses.setUserText(classTitle.getText());
  }
});

这完美(第一次!)。