Adding elements to a JList

纵饮孤独 提交于 2019-11-27 06:19:10

问题


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.


回答1:


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




回答2:


Add to the ListModel rather than directly to the JList itself. Currently you are using the add method which does not affect the contents of the list. DefaultListModel is mutable so can be updated at runtime.

Declaring:

JList<String> jList1 = new JList<String>(new DefaultListModel<String>());

Adding:

((DefaultListModel)jList1.getModel()).addElement(Customers[i].getName());


来源:https://stackoverflow.com/questions/16214480/adding-elements-to-a-jlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!