问题描述
我有一个包含客户名称的对象数组,如下所示: Customers []
I have an array of objects that contain the name of customers, like this: Customers[]
按下按钮后如何自动将这些元素添加到现有的JList中?我尝试过这样的事情:
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());
}
但我总是犯错。我怎么解决这个问题?我正在研究NetBeans。
出现的错误是找不到合适的add(String)方法。顺便说一下,我的方法getName在String中返回客户名称。
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.
推荐答案
您使用的 add
方法是 Container#add
方法,所以肯定不是你需要的。
你需要改变 ListModel
,例如
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() );
}
编辑:
我调整了代码片段以添加名称直接到模型。这避免了对自定义渲染器的需求
I adjusted the code snippet to add the names directly to the model. This avoids the need for a custom renderer
这篇关于将元素添加到JList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!