how to bind ArrayList to JList
Asked Answered
S

5

5

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.

Scraperboard answered 21/6, 2011 at 5:11 Comment(1)
possible duplicate of Java ArrayLists into JListStarveling
M
14

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

JList list = new JList(arl.toArray()); 
Maryjomaryl answered 21/6, 2011 at 5:17 Comment(1)
What is the use of clone() not here.in all aspects?Scraperboard
P
6
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).

Phatic answered 27/5, 2013 at 13:22 Comment(0)
O
3
JList jList = new JList(arrayList.toArray());
Overshine answered 21/6, 2011 at 5:15 Comment(0)
S
1
JList list = new JList(arl.toArray());
Schellens answered 21/6, 2011 at 5:16 Comment(0)
A
1

Another option is:

DefaultListModel Jlista = new DefaultListModel();

public Form1() {

 jList1.setModel(Jlista);

}

public void yourFunction(){
 Jlista.addElement("newElement");
}
Ahithophel answered 16/2, 2017 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.