JList.getModel() ClassCastException

早过忘川 提交于 2019-11-29 04:36:14

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

If you need access to the underlying model you should create it, set it in the JList constructor and retain it yourself.

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

  1. Select your jList
  2. In properties, click the model button
  3. select the "Custom code" option
  4. Write new DefaultListModel ()

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!