7.4.1. 在表格列中显示图片

为了扩展上一个任务,我们在 Employee 浏览界面上将图片作为员工头像添加到表格中。

图片可以单独显示在某列,也可以跟其它内容一起显示在现有的列中。这两种情况都使用 Table.ColumnGenerator 接口。

下面是 Employee 浏览界面 XML 描述的一个片段:

  1. <groupTable id="employeesTable"
  2. width="100%"
  3. dataContainer="employeesDc">
  4. <actions>
  5. <action id="create" type="create"/>
  6. <action id="edit" type="edit"/>
  7. <action id="remove" type="remove"/>
  8. </actions>
  9. <columns>
  10. <column id="name"/>
  11. </columns>
  12. <rowsCount/>
  13. <buttonsPanel id="buttonsPanel"
  14. alwaysVisible="true">
  15. <button id="createBtn" action="employeesTable.create"/>
  16. <button id="editBtn" action="employeesTable.edit"/>
  17. <button id="removeBtn" action="employeesTable.remove"/>
  18. </buttonsPanel>
  19. </groupTable>

要在 name 列中将员工姓名与图片显示在一行,我们要修改此列中数据的标准展示方式。将使用 HBoxLayout 容器并将 Image 组件放入其中:

  1. import com.company.demo.entity.Employee;
  2. import com.haulmont.cuba.core.entity.FileDescriptor;
  3. import com.haulmont.cuba.gui.UiComponents;
  4. import com.haulmont.cuba.gui.components.*;
  5. import com.haulmont.cuba.gui.screen.LookupComponent;
  6. import com.haulmont.cuba.gui.screen.*;
  7. import javax.inject.Inject;
  8. @UiController("sales_Employee.browse")
  9. @UiDescriptor("employee-browse.xml")
  10. @LookupComponent("employeesTable")
  11. @LoadDataBeforeShow
  12. public class EmployeeBrowse extends StandardLookup<Employee> {
  13. @Inject
  14. private UiComponents uiComponents;
  15. @Inject
  16. private GroupTable<Employee> employeesTable;
  17. @Subscribe
  18. protected void onInit(InitEvent event) { (1)
  19. employeesTable.addGeneratedColumn("name", entity -> {
  20. Image image = uiComponents.create(Image.NAME); (2)
  21. image.setScaleMode(Image.ScaleMode.CONTAIN);
  22. image.setHeight("40");
  23. image.setWidth("40");
  24. FileDescriptor imageFile = entity.getImageFile(); (3)
  25. image.setSource(FileDescriptorResource.class)
  26. .setFileDescriptor(imageFile);
  27. Label userLogin = uiComponents.create(Label.NAME); (4)
  28. userLogin.setValue(entity.getName());
  29. userLogin.setAlignment(Component.Alignment.MIDDLE_LEFT);
  30. HBoxLayout hBoxLayout = uiComponents.create(HBoxLayout.NAME); (5)
  31. hBoxLayout.setSpacing(true);
  32. hBoxLayout.add(image);
  33. hBoxLayout.add(userLogin);
  34. return hBoxLayout;
  35. });
  36. }
  37. }
1onInit() 方法调用 addGeneratedColumn() 方法,此方法接收两个参数:列标识符和 Table.ColumnGenerator 接口的实现。后者用于在 name 列中定义数据的自定义显示方式。
2在这个方法中,我们使用 UiComponents 接口创建一个 Image 组件,设置了组件的缩放模式(设置为 CONTAIN ) 及其尺寸参数。
3然后获取存储在 File Storage 中图片的 FileDescriptor 实例。该图片的链接存储在 Employee 实体的 imageFile 属性中。FileDescriptorImageResource 资源类型用于设置 Image 组件的资源。
4我们将在图片旁边的 Label 组件中显示 name 属性。
5我们将 ImageLabel 组件包装到 HBoxLayout 容器,并使 addGeneratedColumn() 方法返回此容器作为新的表格单元格布局。

images in table

另外,也可以使用 XML 的generator 属性以更具“声明式”的方式进行定义。