Error removing item from JList

I have a problem removing an item from a JList, my application is a client server application, the client has a JList (view). The server has the actual JList data as a vector. When a specific action occurs on the client, the server must remove the item from the vector and then update the view on the client. I tried to get the vector after deleting from the server and then building a new JList and then setting it in the view, but no update happens.

What are the possible ways to do this?

note: I used the DefaultListModel like this:

DefaultListModel model=(DefaultListModel)myList.getModel();
model.removeElement(myElement);
myList.setModel(model);

      

but it gives a ClassCastException at runtime, it says that javax.swing.JList cannot be cast to javax.swing.DefaultListModel

+3


source to share


1 answer


You can add items to the list simply by passing it Vector

in the constructor or using a method setListData

, but this is not the best way to do it.

Usually you want to use an implementation ListModel

like DefaultListModel

. It defines the methods of data processing ( addElement

, removeElement

, ...).

You can reduce the amount of data exchanged between the server and client (s) by requesting the server only for the remote item and not getting all the data.



Update . Now I can see that you are using a model. The standard implementation of the model is JList

not type specific DefaultListModel

. You can set the model in the constructor JList

when you instantiate JList

at the beginning.

DefaultListModel model = new DefaultListModel();
JList list = new JList(model);

      

Don't instantiate again, you only need to do it once. Then you can use the code you entered, but after removing the element, you don't need to call the method setModel()

.

+2


source







All Articles