Question

This is my code:

     private static final long serialVersionUID = 1L;
  /* The data as a list of Persons.
  */
  private static List<PersonModel> personData = new ArrayList<PersonModel>();

  public static JList<PersonModel> jlist;


  public void init() {

      // Add some sample data
      personData.add(new PersonModel("Hans", "Muster"));
      personData.add(new PersonModel("Ruth", "Mueller"));
      personData.add(new PersonModel("Heinz", "Kurz"));
      personData.add(new PersonModel("Cornelia", "Meier"));
      personData.add(new PersonModel("Werner", "Meyer"));
      personData.add(new PersonModel("Lydia", "Kunz"));
      personData.add(new PersonModel("Anna", "Best"));
      personData.add(new PersonModel("Stefan", "Meier"));
      personData.add(new PersonModel("Martin", "Mueller"));

      String dataQ = " ";


      for(int i = 0; i < personData.size(); i++){
            dataQ = personData.get(i).getLastName() + " " + personData.get(i).getFirstName();
      }
      String[] arr = new String[] { dataQ };
      jlist = new JList(arr);

But it only displays the last record. How can I display all of the records/values? Any ideas? Thanks.

Was it helpful?

Solution

You are using String variable and not array of String,So while iterating in loop it is storing last value of Arraylist personData in dataQ variable.Try this,

int size=personData.size();//get size of personData
String dataQ[]=new String[size];//change String dataQ to dataQ[]; 

 for(int i = 0; i < personData.size(); i++)
      {
            dataQ[i] = personData.get(i).getLastName() + " " + personData.get(i).getFirstName();
      }

OTHER TIPS

You could just use the Jlist#toArray method to get an array representation of your list.

jList = new JList(personData.toArray(new PersonModel[personData.size()]);

At this point, of course, you would need to supply a ListCelLRenderer to render the values.

A better approach would be to use a ListModel directly. Something like...

public class PersonListModel extends AbstractListModel<PersonModel>{

    private List<PersonModel> people;

    public PersonListModel(List<PersonModel> people) {
        this.people = people;
    }

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

    @Override
    public PersonModel getElementAt(int index) {
        return people.get(index);
    }

}

Then you could just do...

JList jList = new JList(new PersonListModel(personData));

Check out How to use lists for more details

 String[] arr = new String[]; 

for(int i = 0; i < personData.size(); i++){
            dataQ = personData.get(i).getLastName() + " " + personData.get(i).getFirstName();
arr [i] = dataQ;
      }

      jlist = new JList(arr);

try this

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top