Java 向 JList 添加元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16214480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:49:34  来源:igfitidea点击:

Adding elements to a JList

javaswingjlistdefaultlistmodel

提问by Little

I have an array of objects that contain the name of customers, like this: Customers[]

我有一个包含客户名称的对象数组,如下所示: Customers[]

How I can add those elements to an existing JList automatically after I press a button? I have tried something like this:

按下按钮后,如何将这些元素自动添加到现有 JList 中?我试过这样的事情:

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.

但我总是犯错误。我该如何解决?我正在研究 NetBeans。 出现的错误是“为 add(String) 找到了不合适的方法。顺便说一下,我的方法 getName 正在以字符串形式返回客户的姓名。

回答by Reimeus

Add to the ListModelrather than directly to the JListitself. Currently you are using the addmethod which does not affect the contents of the list. DefaultListModelis mutable so can be updated at runtime.

添加到ListModel而不是直接添加到JList本身。目前您正在使用不影响列表内容的add方法。DefaultListModel是可变的,因此可以在运行时更新。

Declaring:

声明:

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

Adding:

添加:

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

回答by Robin

The addmethod you are using is the Container#addmethod, so certainly not what you need. You need to alter the ListModel, e.g.

add您使用的方法是Container#add方法,所以当然你不用什么。你需要改变ListModel,例如

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

我调整了代码片段以将名称直接添加到模型中。这避免了对自定义渲染器的需要