我创建了一个有四列的网格。第一列显示名称,其他三列代表不同的角色。每个这三列都填充了复选框,以便将特定角色分配给特定名称。到目前为止,我只完成了这些。
在每列和每行中,只允许选择一个复选框。因此,每个复选框列总共只有一个选择。我该如何实现这个功能?
编辑:我意识到我可能完全误解了问题。如果您想要三列,每列都有多个复选框,每列只能选择一个,请在每列中使用RadioButtonGroup,并将每个RadioButtonGroup绑定到您的GridItem类的不同枚举字段上。
与其展示如何在每个CheckBox中只选择一个的情况下做出三个列,我将展示另一种方法来实现有关项目的相同信息。
原因是��想要实现的解决方案并不容易实现,因为每个CheckBox在其不知道同一项目的其他CheckBox的范围内定义。因此,您需要在项类的setter中实现自己的仅选择一个规则,这不是最理想的。我的意思是,这是可能的,但我宁愿改变结构以适应更合适的结构。通常,您不希望在bean类中放置此类业务逻辑。
我将如何解决手头的问题?
创建一个新的枚举,它将替换您项目类中的所有3个布尔字段。现在,在您的网格中,您只需要一个用于选择枚举的ComboBox列。
我选择枚举,因为它完全符合您此处的需求。使用枚举,您可以有多个选项,但只能选择一个(或没有)。
为了更好地说明我的意思,让我们使用一个名为Foo
的示例类来表示网格项。您的版本有3个布尔值,您的三个网格复选框绑定到这些布尔值上。让我们称它们为isA
、isB
和isC
。
// your version of the griditem class
public class Foo {
private boolean isA, isB, isC = false;
// constructor, getters, setters
}
// how the columns are added in the grid (approximately) (without editor):
Grid<Foo> grid = new Grid<>();
grid.addComponentColumn((item) -> {
CheckBox checkBox = new CheckBox();
checkBox.setValue(item.isA());
checkBox.addValueChangeListener(event -> item.setA(event.getValue()); // inside setA() method you need to set isB and isC to false if the new value is true. No good!
return checkBox;
});
grid.addComponentColumn((item) -> {
CheckBox checkBox = new CheckBox();
checkBox.setValue(item.isB());
checkBox.addValueChangeListener(event -> item.setB(event.getValue()); // inside setB() method you need to set isB and isC to false if the new value is true. No good!
return checkBox;
});
grid.addComponentColumn((item) -> {
CheckBox checkBox = new CheckBox();
checkBox.setValue(item.isC());
checkBox.addValueChangeListener(event -> item.setC(event.getValue()); // inside setC() method you need to set isB and isA to false if the new value is true. No good!
return checkBox;
});
以下是我所做的更改后的样子
public class Foo {
private AbcEnum abcEnum = null;
// constructor, getters, setters
}
public Enum AbcEnum {
A,
B,
C;
}
// how the columns are added (without editor):
Grid<Foo> grid = new Grid<>();
grid.addComponentColumn((item) -> {
ComboBox<AbcEnum> comboBox = new ComboBox<>();
comboBox.setValue(item.getAbcEnum());
comboBox.addValueChangeListener(event -> item.setAbcEnum(item.getValue()));
return comboBox;
});