How to create a List in Java

A list component displays a scrolling list from which the user can select one or more items.A list differs from a combo box in that two or more items in the list can be made visible at
all times. In Figure 8.2, the component to the right of the text "Select Purchase" is an example of a list. With Swing lists, we explicitly manipulate two models: the list and selection models. A list model is declared, list elements are added to this model, and the model is used when creating the list object. First declare a list model of type DefaultListModel. For example,

DefaultListModel shoppingListModel;


Then declare a list object to be of type JList. For example,

JList shoppingList;

Then create the list model object using the javax.swing.DefaultListModel
constructor, as follows:

shoppingListModel = new DefaultListModel();

Individual list elements are added to the model using the
javax.swing.DefaultListModel.addElement method. For example,

shoppingListModel.addElement(''ice axe");

The list object itself is created using the javax.swing.JList constructor, as follows:

shoppingList = new JList(shoppingListModel);

Note the constructor requires the list model as an argument.

To specify that only one item can be selected from the list at any one time, use the setSelectionMode method. For example,

shoppingList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

Other possible argument values are SINGLE_INTERVAL_SELECTION, which allows one contiguous interval to be selected, and MULTIPLE_INTERVAL_SELECTION, which allows multiple intervals to be selected. MULTIPLE_INTERVAL_SELECTION is the default. To set the number of list rows to be made visible, use the javax.swing.JList.setVisibleRowCount method. For example,

shoppingList.setVisibleRowCount(3);
will make three rows of shoppingList visible at any one time. Note that, like text areas, scrollbars are not automatically created for lists by Swing. To add scrollbars, create a scrollpane object, then add the list to the scrollpane object. For example,

JScrollPane sp = new JScrollPane(shoppingList);

No comments:

Post a Comment