Why I cannot add ArrayList directly to Jlist?

后端 未结 4 1653
野的像风
野的像风 2021-01-24 09:07

i am trying to add ArrayList to Jlist, but the only way that I given to understand is that to write the code like this :

ArrayList labels = new Arr         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-24 10:03

    The inclusion of "helper" constructors was meant to make it easier to use the JList with simple data structures.

    The JList (and many Swing components) are actually meant to be used with models that supply the actual data to the view.

    The original design goes way back before Swing was incorporated into the main library (prior to JDK 1.3) and just before the collections API was introduced, so it's likely that the original developers didn't have List available to them (hence the inclusion of Vector).

    It's likely that no one has seen fit to update the libraries since (partially because it may have been decided that the original constructors shouldn't have been included, but I wasn't at that meeting ;))

    A better/simpler solution would be to create your own model that uses the List as it's data source.

    For example...

    public class MyListModel extends AbstractListModel {
    
        private List people;
    
        public MyListModel(List people) {
            this.people = people;
        }
    
        @Override
        public int getSize() {
            return people.size();
        }
    
        @Override
        public T getElementAt(int index) {
            return people.get(index);
        }
    }
    

    Then you can simply supply it to the JList when ever you need to...

    JList myList = new JList(new MyListModel(listOfMyObjets));
    

提交回复
热议问题