Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
108 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...