且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Vaadin 8网格的网格单元中单击组件以选择单元格行?

更新时间:2021-12-29 23:02:35

我提供了自己当前的解决方案,作为不混淆问题和单独提出可能的评论的答案.这种特殊的方法不是完美的-例如,multiselect的处理不正确-但这只是为了说明我决定如何处理这一点.

I provide my own current solution as an answer to not mess the question and for separate possible comments. This particular one is not perfect - for example multiselect is not handled correctly - but it is just meant to give the idea how i decided to handle this.

想法是为了扩展值提供者,使其拥有对其生成值的网格的引用.前面提到的-除了生成网格列组件之外-还向组件添加了click侦听器.

Idea is to extend a value provider so that it holds a reference to the grid for which it generates values. Beforementioned - in addition to that it generates grid column components - adds click listener to the component.

在处理此程序包时,单击一个组件,并引用了网格和行项目,因此选择/取消选择非常容易.

In this package is handled click on a component and there are references to the grid and row item so select/unselect is quite easy.

@RequiredArgsConstructor // i like lombok
private static class GridCallbackValueProvider
         implements ValueProvider<GridEntity, Layout> {

   private final Grid<GridEntity> grid;

   @Override
   public Layout apply(GridEntity source) {
      AbsoluteLayout al = new AbsoluteLayout();
      al.setWidth("100px");
      al.setHeight("30px");
      al.addStyleName(((source.isValid()) ? "green" : "red" ));
      al.addLayoutClickListener( clickEvent -> {
         if(grid.getSelectedItems().contains(source))
            grid.deselect(source);
         else
            grid.select(source);                
      });
      return al;
    }

}

如果有人感兴趣:在此测试代码中,GridEntity.isValid()仅返回随机布尔值,并用于从以下样式中进行选择:

In case somebody is interested: in this test code GridEntity.isValid() simply returns random boolean value and it is used to choose from styles below:

.green { background-color: green; }
.red { background-color: red; }

添加到网格的过程如下:

And adding to the grid goes like:

grid.addComponentColumn(new GridCallbackValueProvider(grid) )
        .setCaption("status").setId("status").setWidth(140);