Eslam Hamdy
Eslam Hamdy

Reputation: 7386

Issue in removing element from JList

I have a problem in removing an element from a JList, my application is a client server application, the client has the JList (The view). The server have the actual data of the JList in the form of vector. When a certain action occurs on the client the server has to remove an element from the vector and then update the view on the client. I tried to get the vector after removing from the server and then construct a new JList, then set it at the view, but no update occurs.

What are some possible ways to do that?

note: i used the DefaultListModel like that:

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

Upvotes: 3

Views: 513

Answers (1)

Dan D.
Dan D.

Reputation: 32391

You can add elements to a list by just passing it a Vector in the constructor or using the setListData method, but that is not the best way to do it.

You would usually want to use a ListModel implementation like DefaultListModel. It defines methods for handling data (addElement, removeElement,...).

You could reduce the amount of exchanged data between the server and the client(s) by querying the server for the removed element only and not getting all the data.

Update: Now I see you are using a model. The default implementation of a JList model is not of type DefaultListModel. You can set the model in the JList constructor, when you instantiate your JList at the beginning.

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

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

Upvotes: 2

Related Questions