Vaadin Web应用开发教程(44): 使用Container接口管理一组Item
单个属性使用Property接口,一组Property使用Item接口来管理,Container接口则管理一组具有相同属性的Item。Container所包含的Item使用Item标识符(IID)来区分。
Item通过方法addItem()方法向Container添加Item。 查询某个属性可以先通过getItem()取得Item对象,然后再使用getItemProperty()方法,或者直接使用getContainerProperty 方法来读取。
Vaadin在设计Container接口考虑到灵活性和高效性,它包括了一些可选的接口一支持内部Item的排序,索引或者以层次关系来访问Item,从而为实现Table,Tree,Select等UI组件提供了实现基础。
和其它数据模型类似,Container接口也提供了数据变动事件的支持。
Container可以是无序的,有序的,带索引或是支持层次关系,因此可以支持几乎现实中所有数据模型。Vaadin 内部实现支持一些常用的数据源,比如简单的二维表(IndexedContainer)和文件系统(FileSystemContainer)等。
除了上面通用的Container实现,一些UI组件本身就实现了Container接口,比如Select组件。
使用BeanContainer
BeanContainer 为使用内存来管理JavaBean对象的Container类型。每个其中的Item为使用BeanItem封装的Java对象。Item的属性会根据setter, getter 自动识别,因此需要使用的Java Bean具有public 修饰符。也只有同类型的Java Bean对象才可以添加到BeanContainer中。
BeanContainer为一generic 类型,使用时给出所包含的Bean类型和Item 标识符的类型。参考下面例子:
嵌套属性
如果Java Bean有个嵌套的Java Bean类型,而且具有和这个嵌套Java Bean具有1对1的关系,你可以将这个嵌套类的属性添加到Container中,就如同直接包含在其中Java Bean的属性一样。同样此时嵌套的Java Bean也必须具有public 修饰符。
如下例:
先定义两个Java Bean类型,其中EqCoord作为Star的嵌套类,一个Star类对应一个EqCoord,一一对应的关系。使用BeanItemContainer
BeanItemContainer 用来管理一组由BeanItem封装的Java Bean对象。Item的属性会根据setter, getter 自动识别,因此需要使用的Java Bean具有public 修饰符。也只有同类型的Java Bean对象才可以添加到BeanItemContainer中。
BeanItemContainer为BeanContainer的一个特别版本,它不需要指明Item 标识符的类型,而直接使用Item对象来区分Item。因此比BeanContainer使用更简单。class MyCustomFilter implements Container.Filter { protected String propertyId; protected String regex; public MyCustomFilter(String propertyId, String regex) { this.propertyId = propertyId; this.regex = regex; } /** Tells if this filter works on the given property. */ @Override public boolean appliesToProperty(Object propertyId) { return propertyId != null && propertyId.equals(this.propertyId); }