7

I have an array of objects that contain the name of customers, like this: Customers[]

How I can add those elements to an existing JList automatically after I press a button? I have tried something like this:

for (int i=0;i<Customers.length;i++)
{
    jList1.add(Customers[i].getName());
}

But I always get a mistake. How I can solve that? I am working on NetBeans. The error that appears is "not suitable method found for add(String). By the way my method getName is returning the name of the customer in a String.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Little
  • 3,363
  • 10
  • 45
  • 74

1 Answers1

12

The add method you are using is the Container#add method, so certainly not what you need. You need to alter the ListModel, e.g.

DefaultListModel<String> model = new DefaultListModel<>();
JList<String> list = new JList<>( model );

for ( int i = 0; i < customers.length; i++ ){
  model.addElement( customers[i].getName() );
}

Edit:

I adjusted the code snippet to add the names directly to the model. This avoids the need for a custom renderer

Robin
  • 36,233
  • 5
  • 47
  • 99
  • Should it not be `model.addElement( customers[i].getNmae() );`? – MosesA Apr 25 '13 at 12:24
  • @AdegokeA I prefer to add the data elements directly in the model, and decide in the renderer what kind of properties I want to show. But yes, if I wanted to match the code in the question more closely I would need to add the name, and replace the `` by `` in the list and model definition – Robin Apr 25 '13 at 12:34
  • @Robin is there not other easier way to do it? I mean more transparent to the user. I remember in other languages it was as easy as to put list.additem() – Little Apr 25 '13 at 12:56
  • @jma It is as easy as calling `addElement` on the model iso on the view (=the `JList`). Not really difficult I would say – Robin Apr 25 '13 at 13:12
  • 1
    @Robin what does DefaultListModel model = new DefaultListModel<>()? – Little Apr 25 '13 at 13:26
  • It is not as easy as calling `addElement()` because you also need to create a custom renderer. Nobody ever posts the code for the custom renderer. Creating a custom renderer also messes up things like row selection by key stroke, since the default logic uses the toString() method of the Item added to the model to determine which row to select. – camickr Apr 25 '13 at 15:52
  • @camickr I think that problem is solved in the `JXList`, but I am not sure. Anyhow, I adjusted the code snippet to add the names directly to the model – Robin Apr 25 '13 at 18:36
  • @jma That is the Java7 diamond operator, see [this question](http://stackoverflow.com/q/4166966/1076463) – Robin Apr 25 '13 at 18:36
  • should we refresh the Jlist / something? if the content is a string would it be possible if we check by using 'contains' method ? – gumuruh Aug 21 '18 at 02:12