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());
}
...
}
}