Reputation: 141
I have a JTable in my JPanel and i want to know how to save the edited cells. What happens right now is that when i edit a cell and press ENTER, the new data is shown.But when I close the program and open it again, the data changes back to what is originally was.
Pictures:
While editing the JTable:
After restarting program:
Thanks in advance
EDIT:
I want to try to get the data from a .txt file inside my project. I'm not really sure how to do that. I dont know how to get the saved data into a .txt file or how to implement it into a JTable.
Upvotes: 2
Views: 4499
Reputation: 42491
Swing is built with MVC in mind. MVC as you probably know stands for Model View Controller. So Model is somethings that contains data and its decoupled from view which is a graphical representation of the data.
The model is a default table model (or maybe you have another implementation). And the view is a JTable itself. Now it works like this: Controller changes the model. And model sends events to anyone who is interested to know about such a change. Controller in this case is also a JTable (the part of it that allows editing). So in fact after you edit your cell, the table model that stands behind the JTable gets changed (remember, controller knows who is its model so it changes it). Now the model says (in swing it sends events) : "I'm changed" - so there is a change event.
The only problem is that no-one probably handles this event so that the model's change will persist through the restart.
I believe what you should do is: Implement a listener that will take a model and serialize it into file/put into xml file or database - whatever that survives the restart (you can think about the most suitable format).
While I didn't point on specific classes (TableModelListener was already suggested) I thought the overall explanation won't harm here.
Hope, this helps
Upvotes: 1
Reputation: 17945
You should use the TableModelListeners' methods, and trigger a write to disk (in the same format that you use when loading the data) whenever something changes. So, write something like
myTable.getModel().addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
// access the values of the model and save them to the file here
}
});
Upvotes: 2
Reputation: 21748
The DefaultTableModel you probably use (as you do not talk about any other) is Serializable. Obtain it using JTable.getModel() and write to a file upon shutdown using ObjectOutputStream. On the program startup, load it back using ObjectInputStream and set for the table.
If you do not know when your application will terminate, add the Window closing listener and save you table model there.
Of course, there are many other ways to save a table between runs.
Upvotes: 2