Adding elements to a JList
Asked Answered
C

1

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.

Cone answered 25/4, 2013 at 12:15 Comment(3)
What kind of error are you getting? Also, more code will make your question easier to understand.Kavanagh
Smells like a wrong list to add something to!Dissection
How to Use ListsHolzer
B
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

Bellyband answered 25/4, 2013 at 12:22 Comment(9)
Should it not be model.addElement( customers[i].getNmae() );?Oleomargarine
@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 <Customer> by <String> in the list and model definitionBellyband
@Bellyband 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()Cone
@jma It is as easy as calling addElement on the model iso on the view (=the JList). Not really difficult I would sayBellyband
@Bellyband what does DefaultListModel<Customer> model = new DefaultListModel<>()?Cone
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.Conspire
@Conspire 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 modelBellyband
@jma That is the Java7 diamond operator, see this questionBellyband
should we refresh the Jlist / something? if the content is a string would it be possible if we check by using 'contains' method ?Craigcraighead

© 2022 - 2024 — McMap. All rights reserved.