开发者

save/restore Java swing JList Element to/from MySQL

开发者 https://www.devze.com 2023-01-17 05:06 出处:网络
I\'m new to Java (and swing) and looking for a way to save (an开发者_如何学Cd reload it later) all JList elements to Database or in particular MySQL. I read about Java Serializable and cannot find a w

I'm new to Java (and swing) and looking for a way to save (an开发者_如何学Cd 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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号