4

我有以下问题:

  • 带有元素列表的下拉菜单
  • 这些元素中的每一个都有一个固定的键,IChoiceRenderer 实现使用它来查找键的本地化版本(它是在不同包中实现的标准实用渲染器)
  • 本地化键列表位于属性文件中,链接到实例化下拉列表的面板。

是否有一个优雅/可重用的解决方案让下拉列表按字母顺序显示其元素?

4

5 回答 5

2

最后,我认为使用渲染可能是最好的方法。为了使其可重用和高效,我将其隔离在一个行为中。

这是代码:

import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.html.form.AbstractChoice;
import org.apache.wicket.markup.html.form.IChoiceRenderer;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import static java.util.Arrays.sort;

/**
 * This {@link Behavior} can only be used on {@link AbstractChoice} subclasses. It will sort the choices
 * according to their "natural display order" (i.e. the natural order of the display values of the choices).
 * This assumes that the display value implements {@link Comparable}. If this is not the case, you should
 * provide a comparator for the display value. An instance of this class <em>cannot be shared</em> between components.
 * Because the rendering can be costly, the sort-computation is done only once, by default,
 * unless you set to <code>false</code> the <code>sortOnlyOnce</code> argument in the constructor.
 *
 * @author donckels (created on 2012-06-07)
 */
@SuppressWarnings({"unchecked"})
public class OrderedChoiceBehavior extends Behavior {

    // ----- instance fields -----

    private Comparator displayValueComparator;
    private boolean sortOnlyOnce = true;
    private boolean sorted;

    // ----- constructors -----

    public OrderedChoiceBehavior() {
    }

    public OrderedChoiceBehavior(boolean sortOnlyOnce) {
        this.sortOnlyOnce = sortOnlyOnce;
    }

    public OrderedChoiceBehavior(boolean sortOnlyOnce, Comparator displayValueComparator) {
        this.sortOnlyOnce = sortOnlyOnce;
        this.displayValueComparator = displayValueComparator;
    }

    // ----- public methods -----

    @Override
    public void beforeRender(Component component) {
        if (this.sorted && this.sortOnlyOnce) { return;}
        AbstractChoice owner = (AbstractChoice) component;
        IChoiceRenderer choiceRenderer = owner.getChoiceRenderer();
        List choices = owner.getChoices();

        // Temporary data structure: store the actual rendered value with its initial index
        Object[][] displayValuesWithIndex = new Object[choices.size()][2];
        for (int i = 0, valuesSize = choices.size(); i < valuesSize; i++) {
            Object value = choices.get(i);
            displayValuesWithIndex[i][0] = choiceRenderer.getDisplayValue(value);
            displayValuesWithIndex[i][1] = i;
        }

        sort(displayValuesWithIndex, new DisplayValueWithIndexComparator());
        List valuesCopy = new ArrayList(choices);
        for (int i = 0, length = displayValuesWithIndex.length; i < length; i++) {
            Object[] displayValueWithIndex = displayValuesWithIndex[i];
            int originalIndex = (Integer) displayValueWithIndex[1];
            choices.set(i, valuesCopy.get(originalIndex));
        }
        this.sorted = true;
    }

    public Comparator getDisplayValueComparator() {
        return this.displayValueComparator;
    }

    // ----- inner classes -----

    private class DisplayValueWithIndexComparator implements Comparator<Object[]> {

        // ----- Comparator -----

        public int compare(Object[] left, Object[] right) {
            Object leftDisplayValue = left[0];
            Object rightDisplayValue = right[0];
            if (null == leftDisplayValue) { return -1;}
            if (null == rightDisplayValue) { return 1;}

            if (null == getDisplayValueComparator()) {
                return ((Comparable) leftDisplayValue).compareTo(rightDisplayValue);
            } else {
                return getDisplayValueComparator().compare(leftDisplayValue, rightDisplayValue);
            }
        }
    }
}
于 2012-06-07T14:06:26.123 回答
1

如果您想要一个基于 Wicket 的解决方案,您可以尝试使用以下内容对列表进行排序:

public class ChoiceRendererComparator<T> implements Comparator<T> {

    private final IChoiceRenderer<T> renderer;

    public ChoiceRendererComparator(IChoiceRenderer<T> renderer) {
        this.renderer = renderer;
    }

    @SuppressWarnings("unchecked")
    public int compare(T o1, T o2) {
        return ((Comparable<Object>) renderer.getDisplayValue(o1)).compareTo(renderer.getDisplayValue(o2));
    }
}

用法:

    List<Entity> list = ...
    IChoiceRenderer<Entity> renderer = ...
    Collections.sort(list, new ChoiceRendererComparator<Entity>(renderer));
    DropDownChoice<Entity> dropdown = new DropDownChoice<Entity>("dropdown", list, renderer);
于 2012-05-23T07:10:53.360 回答
1

使用 Java 的Collat ​​or 使用 DropDownChoice 的这个扩展(基本上区域敏感排序 - 考虑国家字符和国家排序规则)

使用 Wicket 6 和 Java 5+ 测试的代码:

import java.text.Collator;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import org.apache.wicket.Session;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;

import com.google.common.collect.Ordering;

/**
 * DropDownChoice which sort its choices (or in HTML's terminology select's options) according it's localized value
 * and using current locale based Collator so it's sorted how it should be in particular language (ie. including national characters, 
 * using right order).
 * 
 * @author Michal Bernhard michal@bernhard.cz 2013
 *
 * @param <T>
 */
public class OrderedDropDownChoice<T> extends DropDownChoice<T> {

    public OrderedDropDownChoice(String id, IModel<? extends List<? extends T>> choices, IChoiceRenderer<? super T> renderer) {
        super(id, choices, renderer);
    }

    public OrderedDropDownChoice(String id, IModel<? extends List<? extends T>> choices) {
        super(id, choices);
    }

    public OrderedDropDownChoice(String id) {
        super(id);
    }

    public OrderedDropDownChoice(
            String id,
            IModel<T> model,
            IModel<? extends List<? extends T>> choices,
                    IChoiceRenderer<? super T> renderer) {

        super(id, model, choices, renderer);
    }

    @Override
    public List<? extends T> getChoices() {
        List<? extends T> unsortedChoices = super.getChoices();
        List<? extends T> sortedChoices = Ordering.from(displayValueAlphabeticComparator()).sortedCopy(unsortedChoices);

        return sortedChoices;
    }

    private Collator localeBasedTertiaryCollator() {
        Locale currentLocale = Session.get().getLocale();
        Collator collator = Collator.getInstance(currentLocale);
        collator.setStrength(Collator.TERTIARY);

        return collator;
    }

    private Comparator<T> displayValueAlphabeticComparator() {

        final IChoiceRenderer<? super T> renderer = getChoiceRenderer();

        return new Comparator<T>() {

            @Override
            public int compare(T o1, T o2) {
                Object o1DisplayValue = renderer.getDisplayValue(o1);
                Object o2DisplayValue = renderer.getDisplayValue(o2);

                return localeBasedTertiaryCollator().compare(o1DisplayValue, o2DisplayValue);
            }
        };

    }


}

复制自https://gist.github.com/michalbcz/7236242

于 2013-10-30T17:06:57.953 回答
0

我们在我公司使用的解决方案是基于 Javascript 的,我们在要排序的下拉列表上设置了一个特殊的 css 类,并使用 jQuery 小技巧进行排序。

于 2012-05-22T13:02:01.133 回答
0

面对同样的问题,我将部分本地化数据从我的 XML 移动到数据库,实现了匹配的解析器,并且能够使用本地化的字符串进行排序。表格设计和休眠配置有点棘手,如下所述:休眠@ElementCollection - 需要更好的解决方案

ResourceLoader 遵循以下原则:

public class DataBaseStringResourceLoader extends ComponentStringResourceLoader {

    private static final transient Logger logger = Logger
            .getLogger(DataBaseStringResourceLoader.class);

    @Inject
    private ISomeDAO someDao;
    @Inject
    private IOtherDao otherDao;
    @Inject
    private IThisDAO thisDao;
    @Inject
    private IThatDAO thatDao;

    @Override
    public String loadStringResource(Class<?> clazz, String key, Locale locale,
            String style, String variation) {
        String resource = loadFromDB(key, new Locale(locale.getLanguage()));
        if (resource == null) {
            resource = super.loadStringResource(clazz, key, locale, style, variation);
        }
        return resource;
    }

    private String loadFromDB(String key, Locale locale) {
        String resource = null;
        if (locale.getLanguage() != Locale.GERMAN.getLanguage()
                && locale.getLanguage() != Locale.ENGLISH.getLanguage()) {
            locale = Locale.ENGLISH;
        }
        if (key.startsWith("some") || key.startsWith("other")
                || key.startsWith("this") || key.startsWith("that")) {
            Integer id = Integer.valueOf(key.substring(key.indexOf(".") + 1));
            ILocalizedObject master;
            if (key.startsWith("some")) {
                master = someDao.findById(id);
            } else if (key.startsWith("other")) {
                master = otherDao.findById(id);
            } else if (key.startsWith("this") ){
                master = thisDao.findById(id);
            } else {
                master = thatDao.findById(id);
            }
            if (master != null && master.getNames().get(locale) != null) {
                resource = master.getNames().get(locale).getName();
            } else if (master == null) {
                logger.debug("For key " + key + " there is no master.");
            }
        }
        return resource;
    }
[...]
    }
于 2012-05-23T09:09:14.437 回答