I am currently attempting to write John Conway's game of life in java using Swing. I have however run into problems regarding JPanel
cells in GridLayout
. Here is the code that is problematic
GameOfLifeFrame(int size, int generations, Random random, boolean[][] grid, final GameOfLife life) {
super("Game of life");
this.size = size;
this.generations = generations;
this.random = random;
this.grid = grid;
this.life = life;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
var contentPane = getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JLabel generationMaker = new JLabel("Generation: ");
add(generationMaker);
JLabel alive = new JLabel("Alive: 0");
add(alive);
var gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(size, size, 0, 0));
contentPane.add(gridPanel);
var cellArray = new javax.swing.JPanel[size][size];
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
var cell = new JPanel();
cellArray[i][j] = cell;
cell.setBorder(BorderFactory.createLineBorder(Color.BLACK));
gridPanel.add(cell);
}
}
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
var button = new JButton();
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
generateGrid(cellArray);
alive.setText("Alive: " + countAlive(life.grid));
incrementGeneration();
generationMaker.setText("Generation #" + generationCounter);
}
});
contentPane.add(button);
setVisible(true);
}
private void generateGrid(JPanel[][] cellArray) {
var grid2 = getGrid();
fillInPanels(cellArray, grid2);
life.grid = grid2;
}
protected void fillInPanels(javax.swing.JPanel[][] panelArray, boolean[][] grid) {
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
if (grid[i][j]) {
panelArray[i][j].setBackground(Color.BLACK);
} else {
panelArray[i][j].setBackground(Color.WHITE);
}
}
}
}
It works fine, and is a great emulator of Conway's game of life, but it has a strange effect where the entire screen doesn't change right away, but you can see the individual cells changing, and not changing right away, right when I press the button. Is this because of double buffering? It works better when there are less cells alive on screen, and that is when it actually starts going quickly.
Here is how it is like on a 35 by 35 size grid
What is the source of the problem and how do I solve it? Please forgive me if I have poor formatting on either the question or the post, this is my first time posting here.
The cause of the problem was that the grid was being redrawn every time I changed the paint color of a tile, from black to white or vice versa. Setting setVisible
to false while fillInPanels
was executing, and setting it back to true afterwards solved the issue.