java JList.getModel() ClassCastException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10375115/
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-10-31 00:45:49  来源:igfitidea点击:

JList.getModel() ClassCastException

javaswingjlist

提问by Stripies

When I call JList<String>.getModel()and cast it to DefaultListModel<String>it gives me this exception.

当我调用JList<String>.getModel()并将其转换DefaultListModel<String>为它时,它给了我这个例外。

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JList 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?

不过也不是每次都这样。大多数时候它运行良好,但其他时候它会抛出这个异常。我不明白为什么会这样。我能做些什么来阻止这种情况发生?

采纳答案by ditkin

You should not assume it is a DefaultListModel. Use the interface ListModel. The JList is returning an internal implementation of ListModel.

你不应该假设它是一个 DefaultListModel。使用接口 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 构造函数中设置它并自己保留它。

回答by Nikola Despotoski

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();

回答by SandroMarques

If you are using NetBeans

如果您使用的是 NetBeans

  1. Select your jList
  2. In properties, click the modelbutton
  3. select the "Custom code" option
  4. Write new DefaultListModel ()
  1. 选择您的jList
  2. 属性中,单击模型按钮
  3. 选择“自定义代码”选项
  4. new DefaultListModel ()

jList custom code

jList自定义代码

回答by Black_Zerg

Before JList<String>.getModel(),you must initialize your object JList<String>.setModel(new DefaultModelList())

JList<String>.getModel(),你必须初始化你的对象之前JList<String>.setModel(new DefaultModelList())