How can I make a list model from a JList
in order to be able to insert an item into it.
I want to use this method: addElement(java.lang.Object item)
Just an alternative method, if someone requires to use a custom ListModel
. Inside the class that implements the list model interface, it would be necessary to create a structure to actually hold the elements like a LinkedList
, like this:
public class MyListModel implements ListModel{
private LinkedList data;
private LinkedList<ListDataListener> listeners;
public MyListModel() {
data = new LinkedList();
listeners = new LinkedList();
}
public void addElement(Object element){
data.add(element);
}
@Override
public int getSize() {
return data.size();
}
@Override
public Object getElementAt(int index) {
return data.get(index);
}
@Override
public void addListDataListener(ListDataListener l) {
listeners.add(l);
}
@Override
public void removeListDataListener(ListDataListener l) {
listeners.remove(l);
}
}
You can also create access methods to do anything related to the LinkedList
, like removeElement(Object element)
, or just make the data LinkedList
public, or use different data structures if necessary. Of course, for a simple implementation it will always be easier to use the models provided with Java.
Java provides implementations of ListModel
already, like DefaultListModel, that you can instantiate and use
For example:
final DefaultListModel model = new DefaultListModel();
model.addElement("one");
model.addElement("two");
model.addElement("three");
final JList list = new JList(model);