Adding items to a JList from ArrayList using DefaultListModel

Ari picture Ari · Nov 24, 2011 · Viewed 43.7k times · Source

I'm trying to add items that are in an ArrayList to a JList which is working when I use the following code:

private void UpdateJList(){
    DefaultListModel<String> model = new DefaultListModel<String>();
    for(Person p : personList){
        model.addElement(p.ToString());
    }
    clientJList.setModel(model);
    clientJList.setSelectedIndex(0);
}

However, If I declare the DefaultListModel outside of the method, the adding increments each item, IE instead of adding one of each item, it adds multiple items. I was just wondering why this happens?

Answer

gprathour picture gprathour · Nov 24, 2011

If you define DefaultListModel outside your update method then it becomes Instance variable so it will be having same value for one instance. Thus if you call this method over and over from same instance it will simply add more values to the existing list. Thus it shows multiple items.

NOTE : declaring DefaultListModel outside function does not cause any problem, making its object outside function is the problem. You can do the following without any problem :

DefaultListModel<String> model;

private void UpdateJList(){
    model = new DefaultListModel<String>();
    for(Person p : personList){
         model.addElement(p.ToString());
    }    
    clientJList.setModel(model);     
    clientJList.setSelectedIndex(0);
}

or you can try clearing the previous values from your model and then adding new values.