JList.getModel()ClassCastException [英] JList.getModel() ClassCastException
问题描述
当我呼叫JList<String>.getModel()
并将其强制转换为DefaultListModel<String>
时,它给了我这个例外.
When I call JList<String>.getModel()
and cast it to DefaultListModel<String>
it gives me this exception.
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JList$4 cannot be cast to javax.swing.DefaultListModel
抛出它的代码:
private JList<String> list = new JList<String>();
((DefaultListModel<String>) list.getModel()).addElement(...);
尽管不是每次都这样做.在大多数情况下,它可以完美运行,但在其他情况下,它会引发此异常.我不明白为什么会这样.我有什么办法可以阻止这种情况的发生?
It doesn't do it every time though. Most of the time it works perfectly, but other times it throws this exception. I don't understand why this is happening. Is there anything I can do to stop this from happening?
推荐答案
您不应假定它是DefaultListModel.使用接口ListModel. JList返回ListModel的内部实现.
You should not assume it is a DefaultListModel. Use the interface ListModel. The JList is returning an internal implementation of ListModel.
如果需要访问基础模型,则应创建它,在JList构造函数中进行设置并自己保留.
If you need access to the underlying model you should create it, set it in the JList constructor and retain it yourself.
这篇关于JList.getModel()ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!