java refreshing an array into jList

前端 未结 2 966
你的背包
你的背包 2021-01-13 04:48

OK so I have a JList and the content is provided with an array. I know how to add elements to an array but I want to know how to refresh a JList... or is it even possible? I

相关标签:
2条回答
  • 2021-01-13 05:24

    One good approach is to create a ListModel to manage the data for you and handle updates.

    Something like:

    DefaultListModel listModel=new DefaultListModel();
    for (int i=0; i<data.length; i++) {
      listModel.addElement(data[i]);
    }
    list=new JList(listModel);
    

    Then you can simply make changes via the list model e.g.

    listModel.addElement("New item");
    listModel.removeElementAt(1); // remove the element at position 1
    
    0 讨论(0)
  • 2021-01-13 05:26

    You just need to supply your own ListModel:

     class MyModel extends AbstractListModel {
         private String[] items;
    
        public MyModel(String[] items) {
            this.items = items;
        }
    
        @Override
        public Object getElementAt(int index) {
            return items[index];
        }
    
        @Override
        public int getSize() {
            return items.length;
        }
    
        public void update() {
            this.fireContentsChanged(this, 0, items.length - 1);
        }
    }
    

    After sorting items, just call update.

    0 讨论(0)
提交回复
热议问题