How can I add/remove JList items after it is created?

Jon Wingfield

All of the constructors of JList, except the one that takes a ListModel as an argument, create and use an implementation of the ListModel interface which does not directly support addition and removal of items. The solution is to create your JList using a ListModel implementation that does support these features. The javax.swing.DefaultListModel is one such implementation. For example:

JList myMutablelist = new JList(new DefaultListModel());
The items within the JLists model can now be changed by the following calls:
String item = "Item";
DefaultListModel dlm = (DefaultListModel)myMutablelist.getModel();
The cast to DefaultListModel is required as the add and remove methods are not defined by the ListModel interface.
See the DefaultListModel Javadoc, JListModel Javadoc and the How to Use Lists section of the Java Tutorial for more details.