tags:

views:

63

answers:

1

I'm new to Java (and swing) and looking for a way to save (and reload it later) all JList elements to Database or in particular MySQL. I read about Java Serializable and cannot find a working code for reference.

A: 

Serialization is not the answer. What you want to do is have a controller that can iterate of the JList Model class, and save the data from each item to a database.

String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);

for(int i = 0; i < dataList.getModel().getSize(); i++) {
    String item = (String)dataList.getModel().getElementAt(i);
    saveItemToDatabase(item);
}

This way, you are only saving the data to the database, and not the UI part of the list, and all the other bits around it that trying to serialize the Jlist would do.

Edit: To save the whole model I would still save the items individually, rather than a BLOB. So, to retrieve the data back from the database, you would do something like

dataList.setListData(loadModelFromDatabase());

public Vector loadModelFromDatabase() {
    Vector listModelData = new Vector();
    ResultSet res = conn.prepareStatement("SELECT * FROM listmodel").executeQuery();
    while(res.next()) {
       listModelData.add(res.getString(1));
    }

    return listModelData;
}
Codemwnci
I'm hoping to get a sample demonstrating how to save the whole ListModel Object from my JList.getModel() method into one BLOB field in database so that I can reload it later easier by using JList.setModel() method.
khairil