Vaadin 洗牌 ListSelect

Vaadin shuffle ListSelect

如何随机排列 ListSelect 的项目?

所以我有一个显示项目的 ListSelect,在我单击一个按钮后,我希望项目按顺序随机排列。

仅供参考:我正在使用 Vaadin 7 和 Eclipse Mars

编辑:

final VerticalLayout layout = new VerticalLayout();
        final Button button = new Button("Run");

        ListSelect select = new ListSelect();
        select.setRows(1000);
        select.setNullSelectionAllowed(false);
        select.addItems("Item1","Item2","Item3","Item3");

        //Shuffle the list
        button.addClickListener();

        layout.addComponents(button, select);
        layout.setMargin(true);
        layout.setSpacing(true);

        setContent(layout);
    }

充分利用 BeanItemContainer class:

    protected void init(VaadinRequest request) {
    final HorizontalLayout layout = new HorizontalLayout();
    final Button button = new Button("Run");

    final ListSelect select = new ListSelect();

    select.setNullSelectionAllowed(false);
    final List<ItemBean> list = new LinkedList();
    //Add elements to list
    list.add(new ItemBean("Item1", 1));
    list.add(new ItemBean("Item2", 2));
    list.add(new ItemBean("Item3", 3));
    list.add(new ItemBean("Item4", 4));
    list.add(new ItemBean("Item5", 5));

    final BeanItemContainer<ItemBean> beanBeanItemContainer = new BeanItemContainer<>(ItemBean.class);
    beanBeanItemContainer.addAll(list);

    select.setContainerDataSource(beanBeanItemContainer);


    //Shuffle the list
    button.addClickListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent clickEvent) {
            select.removeAllItems();

            Collections.shuffle(list);

            beanBeanItemContainer.addAll(list);


        }
    });

    layout.addComponents(button);
    layout.addComponent(select);
    layout.setMargin(true);
    layout.setSpacing(true);

    setContent(layout);
}

而你的 bean class 可以定义如下:

public class ItemBean implements Serializable  {
    String name;
    int id;

    public ItemBean(String name, int id) {
        this.name = name;
        this.id = id;
    }

    @Override
    public String toString() {
        return this.name;   
    }

}

如果您还有其他问题,请告诉我!