Adding elements to a JList

点点圈 提交于 2019-11-28 11:36:09

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

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