Mutante
Mutante

Reputation: 278

Insert data into JList without deleting another

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

Answers (1)

camickr
camickr

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:

  1. Create an instance of the DefaultListModel when you create the JList (and then reference it in your code above), or
  2. In your curret code you get the current DefaultListModel 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

Related Questions