简体   繁体   中英

Adding an item to a JList remove all other items

I need some help about adding items to JList. I work on some "library" kind of project. And I need to add readers to already existing JList. But when I try to add it, JList just resets, removes all the readers and starts adding readers to a new blank JList. But I don't need it to make new list but add it to the already existing one.

Here's my code:

listCtenaru = new JList(vector);
vector = new Vector<String>();

    FileInputStream fos = new FileInputStream("myjlist.bin");
    ObjectInputStream oss = new ObjectInputStream(fos);
    listCtenaru = (JList)oss.readObject();

    listScroll = new JScrollPane();
    listScroll.add(listCtenaru);

and action listener event

public void actionPerformed(ActionEvent e) {
       String jmeno = pole1.getText();
       String prijmeni = pole2.getText();

       listCtenaru.setListData(vector);
       vector.addElement(jmeno +" "+ prijmeni);

       pole1.setText("");
       pole2.setText("");

       pole1.requestFocus();

It seems that your are creating a new model each time you add a reader and you set it on your JList.

I think it will be better to use a ListModel which is more flexible and suited for your JList. See the Java tutorials : http://docs.oracle.com/javase/tutorial/uiswing/components/list.html

Here is the javadoc for JList.setListData(vector) :

Constructs a read-only ListModel from an array of items, and calls setModel with this model. Attempts to pass a null value to this method results in undefined behavior and, most likely, exceptions. The created model references the given array directly. Attempts to modify the array after invoking this method results in undefined behavior.

It stated that you must not modifies the vector after a call on setListData() and it's exactly what you have done here.

To add and remove items in a list, you can use a ListModel :

// To create:
DefaultListModel model = new DefaultListModel();
for(Object item : (Object[])ois.readObject()) {
   model.addElement(item);
}
JList list = new JList(model);

// To add:
model.addElement("New element");

// To save:
oos.writeObject(model.toArray());

Incidentally, it is generally a bad idea to serialize a whole Swing component (like a JList ). Instead, you should just serialize the data in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM