从 jlist 添加元素时出现编译错误
我正在尝试将 Jlist 中的元素添加到另一个 Jlist 中,如果这是正确的术语,则追加 在搜索时,我找到了这段代码并尝试了它,但它不起作用,
ListModel made_model = made_list.getModel(); // 1
Object[] orig_sel = orig_list.getSelectedItems(); // 2
Object[] new_made_model = new Object[made_model.size() + orig_sel.length]; // 3
// this block is 4
int i = 0;
for(;i < made_model.size(); i++)
new_made_model[i] = made_model.getElementAt(i);
for(; i < new_made_model.length; i++)
new_made_model[i] = orig_sel[i - made_model.size());
made_model.setListData(new_made_model); // 5
错误在这一行
made_model.setListData(new_made_model); // 5 它告诉我将 made_model 转换为 Jlist ,我这样做了,但是在运行该类时,我收到此错误
javax.swing.JList$1 无法转换为 javax.swing.JList
I'm trying to add element from a Jlist to another , append if this the correct term
while searching i found this code and tried it but it doesn't work
ListModel made_model = made_list.getModel(); // 1
Object[] orig_sel = orig_list.getSelectedItems(); // 2
Object[] new_made_model = new Object[made_model.size() + orig_sel.length]; // 3
// this block is 4
int i = 0;
for(;i < made_model.size(); i++)
new_made_model[i] = made_model.getElementAt(i);
for(; i < new_made_model.length; i++)
new_made_model[i] = orig_sel[i - made_model.size());
made_model.setListData(new_made_model); // 5
the error is in this line
made_model.setListData(new_made_model); // 5
it tells me to cast made_model to Jlist , which i did but then while running the class , i get this errorjavax.swing.JList$1 cannot be cast to javax.swing.JList
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
setListData()
是 JList 的方法,而不是 ListModel 的方法。您无法将 ListModel 转换为 JList。您的代码应该是:
编辑:
不用使用数组来创建新模型,只需使用 DefaultListModel:
然后您可以直接将对象添加到模型中,而不使用索引:
完成后,将模型添加到列表中:
这样您在使用 3 个数组的索引时不太可能出错。
如果您需要更多帮助,请接受此答案(因为它与编译错误有关)并使用正确的 SSCCE 发布新问题这说明了问题所在。
setListData()
is a method of JList, not of ListModel. You can't cast a ListModel to a JList.Your code should be:
Edit:
Instead of playing with Arrays to create a new model just use a DefaultListModel:
Then you can add Objects directly to the model without using indexes:
When you are finished you add the model to the list:
This way you are less likely to make a mistake when playing with the indexes of the 3 Arrays.
If you need more help then accept this answer (since it was about a compile error) and post a new question with a proper SSCCE that demontrates the problem.