-2

In my Cell class HashMap<String,Image> icons is meant to be initialized just once (on creating the first instance, for example). But in fact such initializer is called each time I create a new Cell instance. What did I misunderstand?

Cell.java

// represents single cell
public class Cell {
    ...
    static final HashMap<String,Image> icons = new HashMap<String, Image>();
    {
        icons_init();
    }
    
    ...
    
    Cell()
    {
        setCovered(true);
    }
    
    ...
    
    private static void icons_init()
    {
        // load icons that represent different cell types and states
        icons.clear();
        try {
        for(int i=0; i<=8; i++)
            {
                // Current cell is open and has N (0-8) mines around (horiz., vert. and diag.)
                icons.put(Integer.toString(i), ImageIO.read(Game.class.getResource("images/"+Integer.toString(i)+".png")));
            }
            icons.put("covered", ImageIO.read(Game.class.getResource("images/coveredCell.png"))); // cell is covered (and has no flag)
            icons.put("covered_flagged", ImageIO.read(MainWindow.class.getResource("images/coveredFlaggedCell.png"))); // cell is covered and has a flag
            icons.put("mined", ImageIO.read(Game.class.getResource("images/minedCell.png"))); // cell is open and mined
            icons.put("mined_flagged", ImageIO.read(Game.class.getResource("images/minedFlaggedCell.png"))); // cell is open, mined and was previously marked with a flag
        }
        catch(IOException ex)
        {
            ex.printStackTrace(); // could not load icon(s) for some reason
        }
    }
    
}

Board.java

    public class Board extends JPanel {
    
    protected ArrayList<Cell> minefield;
    
    public Board(int cols, int rows) {
        ...
        this.minefield = new ArrayList<Cell>(nCols*nRows);
        fieldInit();
    }
    
    protected void fieldInit()
    {
        // initialize an array by filling it with cell objects
        for(int i=0; i<(nRows*nCols); i++)
        {
            minefield.add(new Cell());
        }
        ...
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

2 Answers2

2

The block that you have added is not static initializer block. You are missing static keyword.

Try adding initializer in static block?

static {
        icons_init();
}
Digsb
  • 320
  • 2
  • 8
0

As pointed out by the comments, your code in Cell.java should look like this:

// represents single cell
public class Cell {
    ...
    static final HashMap<String,Image> icons = new HashMap<String, Image>();

    static {
        icons_init();
    }
    
    ...
    
    Cell()
    {
        setCovered(true);
    }
...

With adding the static keyword to the block it becomes a static initializers which is called only once in the beginning when the class is initialized.

jmizv
  • 1,172
  • 2
  • 11
  • 28