Java 如何将 ArrayList 绑定到 JList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6420623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:46:38  来源:igfitidea点击:

how to bind ArrayList to JList

javaswingjlist

提问by

i have a JList and an ArrayList.How to bind the datas in arraylist to the jlist.Are the any alternative methods?

我有一个 JList 和一个 ArrayList。如何将 arraylist 中的数据绑定到 jlist.Are 任何替代方法?

    ArrayList arl = new ArrayList();
    arl.add("1asdsd");
    arl.add("2asdsd");
    arl.add("3asdsd");  
    Object obj = arl.clone();
    JList list = new JList(obj);

how to bind the above code.Now the code give an error.

如何绑定上面的代码。现在代码给出错误。

采纳答案by Oleg Pavliv

You don't need to clone the ArrayList. Just call toArray()

您不需要克隆 ArrayList。只需调用 toArray()

JList list = new JList(arl.toArray()); 

回答by Kal

JList jList = new JList(arrayList.toArray());

回答by Prince John Wesley

JList list = new JList(arl.toArray());

回答by Rauno Veberson

ArrayList<String> aList = new ArrayList<String>();
aList.add("blabla");
aList.add("blublu");
aList.add("blibli");
aList.add("bleble");
DefaultListModel<String> model = new DefaultListModel<String>();
for(String s:aList){
    model.addElement(s);
}
JList<String> contactList = new JList<String>(model);

Advantage of this is that you can later add/remove elements to already instantiated JList by adding elements to model using methods addElement(Obj o) and removeElement(Obj o).

这样做的好处是,您可以稍后通过使用 addElement(Obj o) 和 removeElement(Obj o) 方法向模型添加元素来向已实例化的 JList 添加/删除元素。

回答by Leonardo Mora

Another option is:

另一种选择是:

DefaultListModel Jlista = new DefaultListModel();

public Form1() {

 jList1.setModel(Jlista);

}

public void yourFunction(){
 Jlista.addElement("newElement");
}