Java JList 添加和删除项目 (Netbeans)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23767763/
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
JList adding and removing items (Netbeans)
提问by arnoutvh
I'm trying to add and remove items from my jList (jList1), but It doesn't work. I've searched on stackoverflow for other people with the same problem, but when their problem is solved, I keep getting errors. So this is how I declared the jList:
我正在尝试从我的 jList (jList1) 添加和删除项目,但它不起作用。我已经在 stackoverflow 上搜索了其他有同样问题的人,但是当他们的问题得到解决时,我不断收到错误消息。所以这就是我声明 jList 的方式:
jList1.setModel(new javax.swing.AbstractListModel() {
String [] strings = lijstItems;
public int getSize() {
return strings.length;
}
public Object getElementAt (int i) {
return strings[i];
}
});
So now I made these buttons to add and remove items from the list:
所以现在我制作了这些按钮来添加和删除列表中的项目:
private void addHostActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DefaultListModel model = (DefaultListModel) jList1.getModel();
model.add(2, "item");
// THIS DOES NOT WORK...
}
And
和
private void deleteHostActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
I've tried so many things, but they don't work! Can anyone help me please?
我尝试了很多东西,但它们不起作用!有人可以帮我吗?
Thanks!
谢谢!
采纳答案by Paul Samsotha
You set the model of the list to an AbstractListModel
. You can'tcast the model to a DefaultListModel
. Trying to do so will give you a ClassCastException
So set the model to a DefaultListModel
instead.
您将列表的模型设置为AbstractListModel
. 您不能将模型转换为DefaultListModel
. 尝试这样做会给你一个ClassCastException
所以将模型设置为 a DefaultListModel
。
jList1.setModel(new DefaultListModel());
And you probably want to use DefaultListModel#addElement(element)
instead of adding the element to same index every time, with add(2, element)
而且您可能希望使用DefaultListModel#addElement(element)
而不是每次都将元素添加到相同的索引中add(2, element)
回答by camickr
this is how I declared the jList:
这就是我声明 jList 的方式:
Why are you creating a custom ListModel? Just use the DefaultListModel. There is no need for you to create a custom model to simply store String data.
为什么要创建自定义 ListModel?只需使用 DefaultListModel。您无需创建自定义模型来简单地存储字符串数据。
Then you can read the section from the Swing tutorial on How to Use Listsfor a working example that does exactly what you want by using the "Hire" and "Fire" buttons.
然后,您可以阅读 Swing 教程中关于如何使用列表的部分,作为一个工作示例,该示例通过使用“雇用”和“触发”按钮完全满足您的要求。