如何让 AutoCompleteTextField 接受子字符串

How to get AutoCompleteTextField to accept a substring

我可以使用 AutoCompleteTextField 生成用于 select 项目的字符串列表,但它会将整个字符串放在编辑控件中。我希望它只插入 'name' 字符串。

我应该创建一个包含名称字符串和渲染字符串的模型吗?

我应该覆盖哪些函数来获取所需的字符串、获取值或处理点击?

private Model<String> groupToJoinModel = new Model<String>();

final AutoCompleteTextField<String> field = new AutoCompleteTextField<String>("ac", new Model<String>(""))
{
 private static final long serialVersionUID = 1L;

 @Override
 protected Iterator<String> getChoices(String input)
 {
  List<String> choices = new ArrayList<String>(5);
  // from a database: generate lookup items
  // by concatenating strings: name, type, description
  // code omitted
  return choices.iterator();
 }
};
form.add(field);

groupToJoinModel = (Model<String>) field.getDefaultModel();

// Create a button to perform an action
Button joinGroupsButton = new Button("joinGroupButton")
{
 private static final long serialVersionUID = -4974389888115885756L;
 
 @Override
 public void onSubmit()
 {
  if (groupToJoinModel.getObject() != null)
  { 
   // An action is performed on the contents of the edit control
  }
 }
};
form.add(joinGroupsButton); 

您可以使用AbstarctAutoCompleteRenderer.

AbstractAutoCompleteRenderer<String> autoCompleteRenderer = new AbstractAutoCompleteRenderer<String>() {
                    private static final long serialVersionUID = 1L;

                    protected final String getTextValue(final String bean) {
                        String name;
                        // Do you logic to extract the name from the bean
                        ...
                        ...
                        ...

                        return name;
                    }

                    @Override
                    protected final void renderChoice(final String object, final Response response, final String criteria) {
                        response.write(getTextValue(object));
                    }

                };


final AutoCompleteTextField<String> autoComp = new AutoCompleteTextField<String>("item", new PropertyModel(str, "item"),
                        autoCompleteRenderer) {
                    private static final long serialVersionUID = 1L;

                    @Override
                    protected Iterator<String> getChoices(String arg0) {
                        // Your logic
                        ...
                        ...
                        ...

                        return filteredList.iterator();
                    }

                };

渲染器在自动完成构造函数中传递。