You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

components-selection.asciidoc 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. ---
  2. title: Selection Components
  3. order: 5
  4. layout: page
  5. ---
  6. [[components.selection]]
  7. = Selection Components
  8. Vaadin offers many alternative ways for selecting one or more items. The core
  9. library includes the following selection components, all based on the
  10. [classname]#AbstractSelect# class:
  11. // TODO Only use section numbers here, prefixed with "Section", not include section title
  12. [classname]#ComboBox# (<<components-combobox#components.combobox,"ComboBox">>)::
  13. A drop-down list with a text box, where the user can type text to find matching items.
  14. The component also provides an input prompt and the user can enter new items.
  15. [classname]#ListSelect# (<<components-listselect#components.listselect,"ListSelect">>)::
  16. A vertical list box for selecting items in either single or multiple selection mode.
  17. [classname]#NativeSelect# (<<components-nativeselect#components.nativeselect, "NativeSelect">>)::
  18. Provides selection using the native selection component of the browser, typically a drop-down list for single selection and a multi-line list in multiselect mode.
  19. This uses the [literal]#++<select>++# element in HTML.
  20. [classname]#OptionGroup# (<<components-optiongroup#components.optiongroup,"OptionGroup">>)::
  21. Shows the items as a vertically arranged group of radio buttons in the single selection mode and of check boxes in multiple selection mode.
  22. [classname]#TwinColSelect# (<<components-twincolselect#components.twincolselect, "TwinColSelect">>)::
  23. Shows two list boxes side by side where the user can select items from a list of available items and move them to a list of selected items using control buttons.
  24. In addition, the [classname]#Tree#, [classname]#Table#, and [classname]#TreeTable# components allow special forms of selection.
  25. They also inherit [classname]#AbstractSelect#.
  26. [[components.selection.databinding]]
  27. == Binding Selection Components to Data
  28. The selection components are strongly coupled with the Vaadin Data Model,
  29. described in
  30. <<dummy/../../../framework/datamodel/datamodel-overview.asciidoc#datamodel.overview,"Binding
  31. Components to Data">>. The selectable items in all selection components are
  32. objects that implement the [classname]#Item# interface. The items are contained
  33. in a [classname]#Container#.
  34. All selection components are containers themselves and simply forward all
  35. container operations to the underlying container data source. You can give the
  36. container in the constructor or set it set
  37. [methodname]#setContainerDataSource()#. This is further described in
  38. <<dummy/../../../framework/datamodel/datamodel-container#datamodel.container.intro,"Basic
  39. Use of Containers">>.
  40. [source, java]
  41. ----
  42. // Have a container data source of some kind
  43. IndexedContainer container = new IndexedContainer();
  44. container.addContainerProperty("name", String.class, null);
  45. ...
  46. // Create a selection component bound to the container
  47. OptionGroup group = new OptionGroup("My Select", container);
  48. ----
  49. If you do not bind a selection component to a container data source, a default
  50. container is used. It is usually either an [classname]#IndexedContainer# or a
  51. [classname]#HierarchicalContainer#.
  52. The current selection of a selection component is bound to the
  53. [classname]#Property# interface, so you can get the current selection as the
  54. value of the selection component. Also selection changes are handled as value
  55. change events, as is described later.
  56. [[components.selection.adding]]
  57. == Adding New Items
  58. New items are added with the [methodname]#addItem()# method defined in the
  59. [classname]#Container# interface, described in
  60. <<dummy/../../../framework/datamodel/datamodel-container#datamodel.container.intro,"Basic
  61. Use of Containers">>.
  62. [source, java]
  63. ----
  64. // Create a selection component
  65. ComboBox select = new ComboBox("My ComboBox");
  66. // Add items with given item IDs
  67. select.addItem("Mercury");
  68. select.addItem("Venus");
  69. select.addItem("Earth");
  70. ----
  71. The [methodname]#addItem()# method creates an empty [classname]#Item#, which is
  72. identified by its __item identifier__ (IID) object, given as the parameter. This
  73. item ID is by default used also as the caption of the item, as described in more
  74. detail later.
  75. We emphasize that [methodname]#addItem()# is a factory method that __takes an
  76. item ID, not the actual item__ as the parameter - the item is returned by the
  77. method. The item is of a type that is specific to the container and has itself
  78. little relevance for most selection components, as the properties of an item may
  79. not be used in any way (except in [classname]#Table#), only the item ID.
  80. The item identifier is typically a string, in which case it can be used as the
  81. caption, but can be any object type. We could as well have given integers for
  82. the item identifiers and set the captions explicitly with
  83. [methodname]#setItemCaption()#. You could also add an item with the
  84. parameterless [methodname]#addItem()#, which returns an automatically generated
  85. item ID.
  86. [source, java]
  87. ----
  88. // Create a selection component
  89. ComboBox select = new ComboBox("My Select");
  90. // Add an item with a generated ID
  91. Object itemId = select.addItem();
  92. select.setItemCaption(itemId, "The Sun");
  93. // Select the item
  94. select.setValue(itemId);
  95. ----
  96. Some container types may support passing the actual data object to the add
  97. method. For example, you can add items to a [classname]#BeanItemContainer# with
  98. [methodname]#addBean()#. Such implementations can use a separate item ID object,
  99. or the data object itself as the item ID, as is done in [methodname]#addBean()#.
  100. In the latter case you can not depend on the default way of acquiring the item
  101. caption; see the description of the different caption modes later.
  102. The next section describes the different options for determining the item
  103. captions.
  104. [[components.selection.captions]]
  105. == Item Captions
  106. The displayed captions of items in a selection component can be set explicitly
  107. with [methodname]#setItemCaption()# or determined from the item IDs or item
  108. properties. The caption determination is defined with the __caption mode__, any
  109. of the modes in the [classname]#AbstractSelect.ItemCaptionMode# enum, which you
  110. can set with [methodname]#setItemCaptionMode()#. The default mode is
  111. [parameter]#EXPLICIT_DEFAULTS_ID#, which uses the item identifiers for the
  112. captions, unless given explicitly.
  113. In addition to a caption, an item can have an icon. The icon is set with
  114. [methodname]#setItemIcon()#.
  115. The caption modes defined in [classname]#ItemCaptionMode# are the following:
  116. EXPLICIT_DEFAULTS_ID:: This is the default caption mode and its flexibility allows using it in most
  117. cases. By default, the item identifier will be used as the caption. The
  118. identifier object does not necessarily have to be a string; the caption is
  119. retrieved with [methodname]#toString()# method. If the caption is specified
  120. explicitly with [methodname]#setItemCaption()#, it overrides the item
  121. identifier.
  122. +
  123. [source, java]
  124. ----
  125. // Create a selection component
  126. ComboBox select = new ComboBox("Moons of Mars");
  127. select.setItemCaptionMode(
  128. ItemCaptionMode.EXPLICIT_DEFAULTS_ID);
  129. // The given item ID is also used as the caption
  130. select.addItem(new Integer(1));
  131. // Set item caption for this item explicitly
  132. select.addItem(2); // same as "new Integer(2)"
  133. select.setItemCaption(2, "Deimos");
  134. ----
  135. EXPLICIT:: Captions must be explicitly specified with [methodname]#setItemCaption()#. If
  136. they are not, the caption will be empty. Such items with empty captions will
  137. nevertheless be displayed in the selection component as empty items. If they
  138. have an icon, they will be visible.
  139. ICON_ONLY:: Only icons are shown, captions are hidden.
  140. ID:: String representation of the item identifier object is used as caption. This is
  141. useful when the identifier is a string, and also when the identifier is an
  142. complex object that has a string representation. For example:
  143. +
  144. [source, java]
  145. ----
  146. ComboBox select = new ComboBox("Inner Planets");
  147. select.setItemCaptionMode(ItemCaptionMode.ID);
  148. // A class that implements toString()
  149. class PlanetId extends Object
  150. implements Serializable {
  151. String planetName;
  152. PlanetId (String name) {
  153. planetName = name;
  154. }
  155. public String toString () {
  156. return "The Planet " + planetName;
  157. }
  158. }
  159. // Use such objects as item identifiers
  160. String planets[] = {"Mercury", "Venus",
  161. "Earth", "Mars"};
  162. for (int i=0; i<planets.length; i++)
  163. select.addItem(new PlanetId(planets[i]));
  164. ----
  165. INDEX::
  166. Index number of item is used as caption.
  167. This caption mode is applicable only to data sources that implement the [interfacename]#Container.Indexed# interface.
  168. If the interface is not available, the component will throw a
  169. [classname]#ClassCastException#.
  170. The [classname]#AbstractSelect# itself does not implement this interface, so the mode is not usable without a separate data source.
  171. An [classname]#IndexedContainer#, for example, would work.
  172. ITEM:: [classname]#String# representation of item, acquired with
  173. [methodname]#toString()#, is used as the caption. This is applicable mainly when
  174. using a custom [classname]#Item# class, which also requires using a custom
  175. [classname]#Container# that is used as a data source for the selection
  176. component.
  177. PROPERTY:: Item captions are read from the [classname]#String# representation of the
  178. property with the identifier specified with
  179. [methodname]#setItemCaptionPropertyId()#. This is useful, for example, when you
  180. have a container that you use as the data source for the selection component,
  181. and you want to use a specific property for caption.
  182. +
  183. In the example below, we bind a selection component to a bean container and use
  184. a property of the bean as the caption.
  185. +
  186. [source, java]
  187. ----
  188. /** A bean with a "name" property. */
  189. public class Planet implements Serializable {
  190. int id;
  191. String name;
  192. public Planet(int id, String name) {
  193. this.id = id;
  194. this.name = name;
  195. }
  196. ... setters and getters ...
  197. }
  198. public void captionproperty(
  199. VerticalLayout layout) {
  200. // Have a bean container to put the beans in
  201. BeanItemContainer<Planet> container =
  202. new BeanItemContainer<Planet>(
  203. Planet.class);
  204. // Put some example data in it
  205. container.addItem(
  206. new Planet(1, "Mercury"));
  207. container.addItem(new Planet(2, "Venus"));
  208. container.addItem(new Planet(3, "Earth"));
  209. container.addItem(new Planet(4, "Mars"));
  210. // Create a selection component bound
  211. // to the container
  212. ComboBox select = new ComboBox("Planets",
  213. container);
  214. // Set the caption mode to read the
  215. // caption directly from the 'name'
  216. // property of the bean
  217. select.setItemCaptionMode(
  218. ItemCaptionMode.PROPERTY);
  219. select.setItemCaptionPropertyId("name");
  220. ...
  221. ----
  222. [[components.selection.getset]]
  223. == Getting and Setting Selection
  224. A selection component provides the current selection as the property of the
  225. component (with the [classname]#Property# interface). The property value is an
  226. item identifier object that identifies the selected item. You can get the
  227. identifier with [methodname]#getValue()# of the [classname]#Property# interface.
  228. You can select an item with the corresponding [methodname]#setValue()# method.
  229. In multiselect mode, the property will be an unmodifiable set of item
  230. identifiers. If no item is selected, the property will be [parameter]#null# in
  231. single selection mode or an empty collection in multiselect mode.
  232. The [classname]#ComboBox# and [classname]#NativeSelect# will show empty
  233. selection when no actual item is selected. This is the __null selection item
  234. identifier__. You can set an alternative ID with
  235. [methodname]#setNullSelectionItemId()#. Setting the alternative null ID is
  236. merely a visual text; the [methodname]#getValue()# will still return
  237. [parameter]#null# value if no item is selected, or an empty set in multiselect
  238. mode.
  239. [[components.selection.valuechange]]
  240. == Handling Selection Changes
  241. The item identifier of the currently selected item will be set as the property
  242. of the selection component. You can access it with the [methodname]#getValue()#
  243. method of the [classname]#Property# interface of the component. Also, when
  244. handling selection changes with a [classname]#Property.ValueChangeListener#, the
  245. [classname]#ValueChangeEvent# will have the selected item as the property of the
  246. event, accessible with the [methodname]#getProperty()# method.
  247. [source, java]
  248. ----
  249. // Create a selection component with some items
  250. ComboBox select = new ComboBox("My Select");
  251. select.addItems("Io", "Europa", "Ganymedes", "Callisto");
  252. // Handle selection change
  253. select.addValueChangeListener(event -> // Java 8
  254. layout.addComponent(new Label("Selected " +
  255. event.getProperty().getValue())));
  256. ----
  257. The result of user interaction is shown in
  258. <<figure.components.selection.valuechange>>.
  259. [[figure.components.selection.valuechange]]
  260. .Selected Item
  261. image::img/select-selected1.png[width=30%, scaledwidth=40%]
  262. [[components.selection.newitems]]
  263. == Allowing Adding New Items
  264. Some selection components can allow the user to add new items. Currently, only
  265. [classname]#ComboBox# allows it, when the user types in a value and presses
  266. kbd:[Enter]. You need to enable the mode with [methodname]#setNewItemsAllowed(true)#.
  267. Setting the component also in immediate mode may be necessary, as otherwise the
  268. item would not be added immediately when the user interacts with the component,
  269. but after some other component causes a server
  270. request.
  271. // TODO This could be a bug
  272. [source, java]
  273. ----
  274. myselect.setNewItemsAllowed(true);
  275. myselect.setImmediate(true);
  276. ----
  277. The user interface for adding new items depends on the selection component. The
  278. regular [classname]#ComboBox# component allows you to simply type the new item
  279. in the combo box and hit kbd:[Enter] to add it.
  280. Adding new items is not possible if the selection component is read-only or is
  281. bound to a [classname]#Container# that does not allow adding new items. An
  282. attempt to do so may result in an exception.
  283. [[components.selection.newitems.handling]]
  284. === Handling New Items
  285. Adding new items is handled by a [interfacename]#NewItemHandler#, which gets the
  286. item caption string as parameter for the [methodname]#addNewItem()# method. The
  287. default implementation, [classname]#DefaultNewItemHandler#, checks for read-only
  288. state, adds the item using the entered caption as the item ID, and if the
  289. selection component gets the captions from a property, copies the caption to
  290. that property. It also selects the item. The default implementation may not be
  291. suitable for all container types, in which case you need to define a custom
  292. handler. For example, a [classname]#BeanItemContainer# expects the items to have
  293. the bean object itself as the ID, not a string.
  294. ifdef::web[]
  295. [source, java]
  296. ----
  297. // Have a bean container to put the beans in
  298. final BeanItemContainer<Planet> container =
  299. new BeanItemContainer<Planet>(Planet.class);
  300. // Put some example data in it
  301. container.addItem(new Planet(1, "Mercury"));
  302. container.addItem(new Planet(2, "Venus"));
  303. container.addItem(new Planet(3, "Earth"));
  304. container.addItem(new Planet(4, "Mars"));
  305. final ComboBox select =
  306. new ComboBox("Select or Add a Planet", container);
  307. select.setNullSelectionAllowed(false);
  308. // Use the name property for item captions
  309. select.setItemCaptionPropertyId("name");
  310. // Allow adding new items
  311. select.setNewItemsAllowed(true);
  312. select.setImmediate(true);
  313. // Custom handling for new items
  314. select.setNewItemHandler(new NewItemHandler() {
  315. @Override
  316. public void addNewItem(String newItemCaption) {
  317. // Create a new bean - can't set all properties
  318. Planet newPlanet = new Planet(0, newItemCaption);
  319. container.addBean(newPlanet);
  320. // Remember to set the selection to the new item
  321. select.select(newPlanet);
  322. Notification.show("Added new planet called " +
  323. newItemCaption);
  324. }
  325. });
  326. ----
  327. See the http://demo.vaadin.com/book-examples-vaadin7/book#component.select.combobox.newitemhandler[on-line example, window="_blank"].
  328. endif::web[]
  329. [[components.selection.multiple]]
  330. == Multiple Selection
  331. Some selection components, such as [classname]#OptionGroup# and
  332. [classname]#ListSelect# support a multiple selection mode, which you can enable
  333. with [methodname]#setMultiSelect()#. For [classname]#TwinColSelect#, which is
  334. especially intended for multiple selection, it is enabled by default.
  335. [source, java]
  336. ----
  337. myselect.setMultiSelect(true);
  338. ----
  339. As in single selection mode, the property value of the component indicates the
  340. selection. In multiple selection mode, however, the property value is a
  341. [classname]#Collection# of the item IDs of the currently selected items. You can
  342. get and set the property with the [methodname]#getValue()# and
  343. [methodname]#setValue()# methods as usual.
  344. A change in the selection will trigger a [classname]#ValueChangeEvent#, which
  345. you can handle with a [classname]#Propery.ValueChangeListener#. As usual, you
  346. should use [methodname]#setImmediate(true)# to trigger the event immediately
  347. when the user changes the selection. The following example shows how to handle
  348. selection changes with a listener.
  349. [source, java]
  350. ----
  351. // A selection component with some items
  352. ListSelect select = new ListSelect("My Selection");
  353. select.addItems("Mercury", "Venus", "Earth",
  354. "Mars", "Jupiter", "Saturn", "Uranus", "Neptune");
  355. // Multiple selection mode
  356. select.setMultiSelect(true);
  357. // Feedback on value changes
  358. select.addValueChangeListener(
  359. new Property.ValueChangeListener() {
  360. public void valueChange(ValueChangeEvent event) {
  361. // Some feedback
  362. layout.addComponent(new Label("Selected: " +
  363. event.getProperty().getValue().toString()));
  364. }
  365. });
  366. select.setImmediate(true);
  367. ----
  368. [[components.selection.item-icons]]
  369. == Item Icons
  370. You can set an icon for each item with [methodname]#setItemIcon()#, or define an
  371. item property that provides the icon resource with
  372. [methodname]#setItemIconPropertyId()#, in a fashion similar to captions. Notice,
  373. however, that icons are not supported in [classname]#NativeSelect#,
  374. [classname]#TwinColSelect#, and some other selection components and modes. This
  375. is because HTML does not support images inside the native [literal]#++select++#
  376. elements. Icons are also not really visually applicable.