How to convert ArrayList into JList object? java [duplicate]

丶灬走出姿态 提交于 2019-12-18 09:37:58

问题


I have an ArrayList that gets larger as more users join a chatroom. The main JFrame has a list box that displays all currently connected users. But when i try to pass the arraylist into the jframe list i get this following error:

"The method setListData(Object[]) in the type JList is not applicable for the arguments (ArrayList)"

Thanks for your time.


回答1:


You could simply use setListData(arrayList.toArray())

Or you could write your own ListModel, which is backed by the ArrayList, for example...

public class ListBasedListModel<T> extends AbstractListModel<T> {

    private List<T> data;

    public ListBasedListModel(List<T> data) {
        this.data = data;
    }

    @Override
    public int getSize() {
        return data.size();
    }

    @Override
    public T getElementAt(int index) {
        return data.get(index);
    }
}

Then you could just do list.setModel(new ListBasedListModel(arrayList)) or some such

Have a look at How to Use Lists for more details




回答2:


JList myJList = new JList(arrayList.toArray()); //arrayList should be your Array List



回答3:


JList delList = new JList(myArrayList.toArray());


来源:https://stackoverflow.com/questions/34847496/how-to-convert-arraylist-into-jlist-object-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!