JList "add data" - how to add/edit JList data

I don't need to do add data to the JList in my current Java/Swing application, but out of curiosity I did some research to see what you would have to do if you wanted to add data to a JList, and here are the results.

It turns out that if you need to add or edit JList data, you're probably better off creating your data as an instance of a DefaultListModel (as opposed to on object array or Vector).

If you create your data as an instance of a DefaultListModel, you can just change your data, and it will fire off events to update the JList for you. But if you create your data as an object array or Vector, it looks like the only thing you can do is to call the setListData method with a new array or Vector whenever your data changes. In fact, the setListData Javadoc specifically includes this warning about modifying the array or Vector you gave it initially:

Attempts to modify the array (or Vector) after invoking this method results in undefined behavior.

(I always like that "undefined behavior" disclaimer. It basically means, "This is such a bad idea we aren't even going to think about what might happen if you do it", lol.)

JList - add/edit data lesson learned

In summary, if you know the data you want to display in a JList is going to change over time, manage your data as an instance of a DefaultListModel. If it's not going to change, feel free to use an object array or Vector.

Java classes referred to in this article

Here are links to the Java classes that were referred to in this article: