JList.getModel() ClassCastException

前端 未结 4 731
悲哀的现实
悲哀的现实 2020-12-16 21:56

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

Exception in t         


        
相关标签:
4条回答
  • 2020-12-16 22:19

    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();
    
    0 讨论(0)
  • 2020-12-16 22:21

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

    jList custom code

    0 讨论(0)
  • 2020-12-16 22:22

    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.

    0 讨论(0)
  • 2020-12-16 22:29

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

    0 讨论(0)
提交回复
热议问题