lasinicl
lasinicl

Reputation: 161

How to remove elements from a JList passed as a parameter to a method?

public static void removeItems(JList newMenuItemsList)  {
    DefaultListModel listModel = (DefaultListModel) newMenuItemsList.getModel();
    listModel.removeAllElements();       
}

I get an excpetion when I run this code

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: 
     javax.swing.JList$3 cannot be cast to javax.swing.DefaultListModel

How can I overcome this.

Upvotes: 0

Views: 226

Answers (1)

camickr
camickr

Reputation: 324108

Looks to me like you are creating the JList using an Array with code something like:

String[] numbers = { "1001", "1002", "1003" };
JList list1 = new JList<String>( numbers );

If you create a JList using an Array as a parameter then the JList creates a simple implementation of a ListModel for you. This model will be static and can't be changed. That is why you see the JList$3 as the class name of the model.

If you want a dynamic ListModel then you need to use a dynamic model.

An easy way to do this is to use the DefaultComboBoxModel. It allows you to use an Array as you create the instance of the DefaultComboBoxModel.

DefaultComboBoxModel model = new DefaultComboBoxModel(numbers);
JList list2 = new JList<String>( model );

If you want to use the DefaultListModel, then you will need to create the DefaultListModel and then load each item of the Array into the model separately.

DefaulListModel model2 = new DefaultListModel();
JList list2 = new JList<String>( model2 );

for (String number: numbers)
    model2.addElement( number );

Upvotes: 3

Related Questions