简体   繁体   中英

Error copying a JList into an arrayList

I am trying to copy a JList into an array list.

    ArrayList<String> aList= new ArrayList<String>();
    size= list.getModel().getSize(); //list is a JList defined elsewhere
    for(int i=0;i< size ;i++){
        aList.add(list.toString());
    }

But this does not seem to copy the content, instead it is copying the attributes of the JList. Output :javax.swing.JList[,0,0,414x390,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=50331944,maximumSize=,minimumSize=,preferredSize=,fixedCellHeight=-1,fixedCellWidth=-1,horizontalScrollIncrement=-1,selectionBackground=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],selectionForeground=sun.swing.PrintColorUIResource[r=51,g=51,b=51],visibleRowCount=8,layoutOrientation=0]

How to read the content instead ? Is there a more simplified way of doing the same (like toArray() ) ?

Thanks

You are copying the "toString" of a JList, which is just a "human readable" representation of the JList. You have to copy the content, for example by iterating in the model of the JList :

ListModel model : list.getModel();
for (int i=0; i < model.getSize(); i++) {
  aList.add(model.getElementAt(i));
}

Calling JList#toString() cannot in any way work as you seem to think it might work. Please print one call of it to see what it returns. Instead, you'll want to get the JList's model and then get each element that it holds via the getElement(...) method.

aList.add(list.getModel().getElement(i));

Like mention before for (Hovercraft and Thierry) doesn t work, even if used .toString, or get null output. Also do not forget JList come javax. However i suggest use this if is not any event: DefaultListModel for JList, i hope help you.

import java.util.ArrayList;
import javax.swing.DefaultListModel;

public class Jlistinjarry {

    public static void main(String[] args) {
        // TODO Auto-generated method stub


        ArrayList xaList = new ArrayList();
        xaList.add("a");
        xaList.add("b");
        xaList.add("c");
        DefaultListModel model = new DefaultListModel();
        for(String s:xaList){
            model.addElement(s);
        }



         System.out.println( model);


       }
}

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