简体   繁体   中英

Adding items to a JList from ArrayList using DefaultListModel

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM