GWT の CellList でチェック付き ListBox もどきを作る方法

GWT で チェック付き ListBox みたいなウィジェットが提供されていないか探したんですが、そのものズバリなやつは見当たりませんでした。無いものは仕方ないので、CellList 代用。

CompositeCell と SelectionEventManager を使えば、CellList をチェック付き ListBox っぽく振る舞わせることが可能です。

// セルのチェックボックスにチェックが付いたら選択されたことにする
final DefaultSelectionEventManager<Person> selectionManager =
    DefaultSelectionEventManager.createCheckboxManager();

// セルを複数選択できるようにする
final MultiSelectionModel<Person> selectionModel =
    new MultiSelectionModel<Person>();

// チェックボックスとテキストを表示する複合セルを用意
List<HasCell<Person, ?>> hasCells = new ArrayList<HasCell<Person, ?>>();
hasCells.add(new HasCell<Person, Boolean>(){
    private final CheckboxCell cell = new CheckboxCell();
    
    public Cell<Boolean> getCell() {
        return cell;
    }

    public FieldUpdater<Person, Boolean> getFieldUpdater() {
        return null;
    }

    public Boolean getValue(Person object) {
        return selectionModel.isSelected(object);
    }
});
hasCells.add(new HasCell<Person, String>(){
    private final TextCell cell = new TextCell();
    
    public Cell<String> getCell() {
        return cell;
    }

    public FieldUpdater<Person, String> getFieldUpdater() {
        return null;
    }

    public String getValue(Person object) {
        return object.getName();
    }
});
CompositeCell<Person> personCell = new CompositeCell(hasCells);

// CellList 作成
CellList<Person> cellList = new CellList<Person>(personCell);

// 複数選択&チェックが付いたセルを選択できるようにする
cellList.setSelectionModel(selectionModel, selectionManager);