简体   繁体   中英

how to bind ArrayList to JList

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

    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.

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

JList list = new JList(arl.toArray()); 
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).

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

Another option is:

DefaultListModel Jlista = new DefaultListModel();

public Form1() {

 jList1.setModel(Jlista);

}

public void yourFunction(){
 Jlista.addElement("newElement");
}
JList list = new JList(arl.toArray());

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