DefaultListModel Class
Package: javax.swing
DefaultListModel
provides a simple implementation of a list model, which can be used to manage items displayed by a JList
control.
Constructor
Constructor |
Description |
|
Creates a new list model object |
Methods
Method |
Description |
|
Adds an element at the specified position |
|
Adds an element to the end of the list |
|
Removes all elements from the list |
|
Returns |
|
Returns the first element in the list |
|
Returns the element at the specified location |
|
Returns |
|
Returns the last element in the list |
|
Removes the element from the specified position in the list |
|
Removes the specified element from the list |
|
Returns the number of elements in the list |
|
Returns an array containing each element in the list |
When you create the default data model, it’s empty, but you can call the add
or addElement
method to add elements to the list, as in this example:
String[] values =
{“Pepperoni”, “Sausage”, “Linguica”,
“Canadian Bacon”, “Salami”, “Tuna”,
“Olives”, “Mushrooms”, “Tomatoes”,
“Pineapple”, “Kiwi”, “Gummy Worms”};
DefaultListModel model = new DefaultListModel();
for (String value : values)
model.addElement(value);
Here, the elements from the values
array are added to the list model. When you create the JList
control, pass the list model to the JList
constructor, like so:
list = new JList(model);
You can remove an element from the list model by calling the remove
or removeElement
method. To remove all the elements from the model, call the clear
method.