[英]JList.getModel() ClassCastException
When I call JList<String>.getModel()
and cast it to DefaultListModel<String>
it gives me this exception. 当我调用
JList<String>.getModel()
并将其JList<String>.getModel()
为DefaultListModel<String>
它给了我这个异常。
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JList$4 cannot be cast to javax.swing.DefaultListModel
The code that throws it: 抛出它的代码:
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?
有什么办法可以阻止这种情况发生吗?
I experienced this issue. 我遇到过这个问题。 I found this simple workaround:
我找到了这个简单的解决方法:
//----instantiation----
JList mList = new JList();
mList.setModel(new DefaultListModel());
/*---- do whatever you want---- */
//Retain it wherever you want with
DefaultListModel model = (DefaultListModel)mList.getModel();
If you are using NetBeans 如果您使用的是NetBeans
new DefaultListModel ()
new DefaultListModel ()
You should not assume it is a DefaultListModel. 您不应该假设它是DefaultListModel。 Use the interface ListModel.
使用接口ListModel。 The JList is returning an internal implementation of ListModel.
JList返回ListModel的内部实现。
If you need access to the underlying model you should create it, set it in the JList constructor and retain it yourself. 如果需要访问底层模型,则应创建它,在JList构造函数中设置它并自己保留它。
在JList<String>.getModel(),
必须初始化对象JList<String>.setModel(new DefaultModelList())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.