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?
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.
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With