如何随机播放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;
}
}
如果您还有其他问题,请告诉我!