A selection box shows an immediately visible list allowing you to choose one (by default) or more options.
A WSelectionBox corresponds to an HTML <select>
element.
WSelectionBox
is a View widget (see also
Model-View-Controller).
By default a WStringListModel is used. With this model you can associate a
single column of data to the displayed items. The member
methods addItem()
, insertItem()
and
removeItem()
manipulate the model. You can set the model
with setModel()
. See the Combo box section for an example.
A model supports different roles like
JWt.ItemDataRole.DisplayRole
and
JWt.ItemDataRole.UserRole
. The suggestion text for an
item in the drop-down box is associated with a
JWt.ItemDataRole.DisplayRole
. The value, which will be
inserted in the line-edit, corresponding with a suggestion, is
stored as JWt.ItemDataRole.UserRole
) data. If no
UserRole data is available, the behaviour defaults to inserting
the suggestion text itself.
If you want to associate multiple data columns with an item from the combo box then you should assign another model to this control like WStandardItemModel or an implementation of WAbstractTableModel.
Note that there are still other models like WFormModel which and can be used to represent fields in a form.
Use shift and/or ctrl-click to select your pizza toppings...
void SelectionBoxExtended() {
WContainerWidget container = new WContainerWidget();
final WSelectionBox sb2 = new WSelectionBox((WContainerWidget) container);
sb2.addItem("Bacon");
sb2.addItem("Cheese");
sb2.addItem("Mushrooms");
sb2.addItem("Green peppers");
sb2.addItem("Ham");
sb2.addItem("Pepperoni");
sb2.addItem("Red peppers");
sb2.addItem("Turkey");
sb2.setSelectionMode(SelectionMode.Extended);
Set<Integer> selection = new HashSet<Integer>();
selection.add(1);
selection.add(4);
sb2.setSelectedIndexes(selection);
sb2.setMargin(new WLength(10), EnumSet.of(Side.Right));
final WText out = new WText((WContainerWidget) container);
out.addStyleClass("help-block");
sb2.activated()
.addListener(
this,
() -> {
WString selected = new WString();
Set<Integer> newSelection = sb2.getSelectedIndexes();
for (Iterator<Integer> it_it = newSelection.iterator(); it_it.hasNext(); ) {
int it = it_it.next();
if (!(selected.length() == 0)) {
selected.append(", ");
}
selected.append(sb2.getItemText(it));
}
out.setText(new WString("You choose {1}.").arg(selected));
});
}