Controls and layout managers
Components
List models
A frame that lets you add elements to a list
How to work with list models
- To modify the contents of a list, you:
- create a list model to access the data displayed by the list
- pass the list model to the list via the JList constructor
- The list model can be any object that implements the ListModel interface.
- The most commonly used model is the DefaultListModel class.
Some methods of the DefaultListModel class
Method | Description |
---|---|
addElement(Object) | Adds the specified object to the list. |
contains(Object) | Returns a true value if the list contains the specified object. |
get(int) | Returns an Object type for the element at the specified position. |
removeElementAt(int) | Removes the element at the specified position. |
size() | Returns the number of elements in the list. |
clear() | Removes all entries from the list. |
Code that creates a list
String[] descriptions = getProductDescriptions();
productListModel = new DefaultListModel();
for (String s : descriptions)
productListModel.addElement(s);
productList = new JList(productListModel);
productList.setFixedCellWidth(220);
productList.setSelectedIndex(0);
productList.setVisibleRowCount(5);
add(new JScrollPane(productList));
Code that adds an element to the list
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == addButton)
{
String s = descriptionTextField.getText();
productListModel.addElement(s);
}
}