Question

I'm trying to save an ArrayList of GraphicObjects to reload it later. The problem is, I can't load the ArrayList, I always get an empty ArrayList instead of the original ArrayList. There are Objects like [Line@2f06692f] in the original ArrayList.

Here is the important part of my code:

PaintPanel p = new PaintPanel();
...a lot of code...
@Override
public void actionPerformed(ActionEvent e) {
    ArrayList<GraphObject> savedList= new ArrayList<>();
    switch (e.getActionCommand()) {
        case "Save":
            savedList = p.getGraphicList();
            break;

this works and I got the [Line@2f06692f] in savedList.

However, when I try to load it:

        ...some cases...
        case "Load":
            p.setGraphicList(savedList);
            break;

This doesn't work somehow, the savedList is always empty at this point.

This is my PaintPanel class, in which the graphicList is what I want to save.

public class PaintPanel extends JPanel {

    public ArrayList<GraphObject> graphicList = new ArrayList<>();
    ...

I have no clue why...

This is my Interface GraphObject:

import java.awt.*;
import java.io.Serializable;

public interface GraphObject extends Serializable {
    void paint(Graphics2D g2d, boolean tmp);
    void setPaintColor(Color color);
}
Was it helpful?

Solution

It's hard to tell, but it seems to me that your savedList is in local scope to the actionPerformed method, so it goes out of scope when the method ends and isn't actually saved.

Try making savedList a field, perhaps? Hard to give the best recommendation with the amount of code you've provided.

Read more about this in this Scope tutorial

OTHER TIPS

With

savedList = p.getGraphicList(); 

you just copy the reference to exactly the same list. All changes made by PaintPanel later will affect savedList variable also. Please try to change it to

savedList = new ArrayList<>(p.getGraphicList());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top