Reputation: 278
I am adding data that I capture from a jTextField into a jList. Whenever I press a jButton, the jList must be updated with the jTextField data. However, whenever I do this, the previous data is erased, that is, my list always has 1 element. The code is:
DefaultListModel list = new DefaultListModel();
list.addElement(jTextField1.getText());
jList1.setModel(list);
How do I solve this?
Upvotes: 0
Views: 400
Reputation: 324118
However, whenever I do this, the previous data is erased,
DefaultListModel list = new DefaultListModel();
Don't create a new DefaultListModel.
You can either:
DefaultListModel
when you create the JList (and then reference it in your code above), orDefaultListModel
from the JList
using the getModel()
method.Read the section from the Swing tutorial on How to Use Lists. The ListDemo
example does exactly what you want.
Upvotes: 2