3

我在从 JList 中删除元素时遇到问题,我的应用程序是客户端服务器应用程序,客户端具有 JList(视图)。服务器以向量的形式拥有 JList 的实际数据。当客户端发生某个动作时,服务器必须从向量中删除一个元素,然后更新客户端上的视图。我试图在从服务器中删除后获取向量,然后构造一个新的 JList,然后在视图中设置它,但没有发生更新。

有哪些可能的方法来做到这一点?

注意:我这样使用 DefaultListModel:

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

但它在运行时给出了 ClassCastException,它说javax.swing.JList cannot be cast to javax.swing.DefaultListModel

4

1 回答 1

2

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.

于 2013-01-26T19:32:18.457 回答