如何打乱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 类来发挥自己的优势:
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 类可以定义如下:
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;
}
}
如果您有任何其他问题,请告诉我!