Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JList.getModel() ClassCastException

Tags:

java

swing

jlist

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

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?

like image 890
Stripies Avatar asked Apr 29 '12 19:04

Stripies


People also ask

What is JList in Java?

JList is a component that displays a set of Objects and allows the user to select one or more items . JList inherits JComponent class. JList is a easy way to display an array of Vectors . Constructor for JList are : JList(): creates an empty blank list.

How get values from JList?

We can display a value when an item is selected from a JList by implementing MouseListener interface or extending MouseAdapter class and call the getClickCount() method with single-click event (getClickCount() == 1) of MouseEvent class.

Is JList scrollable?

JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane. For example: JScrollPane scrollPane = new JScrollPane(dataList); // Or in two steps: JScrollPane scrollPane = new JScrollPane(); scrollPane.

Which interface is implemented in JList?

Simple, dynamic-content, JList applications can use the DefaultListModel class to maintain list elements. This class implements the ListModel interface and also provides a java.


1 Answers

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();
like image 62
Nikola Despotoski Avatar answered Sep 30 '22 05:09

Nikola Despotoski