I am writing a simple Game of Life program in Java and I have problems reviving it. I have a JComponent class called LifeDraw that displays a grid of pixels with the following drawing method:
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int y = 0; y < lGrid.getHeight(); y++) {
for (int x = 0; x < lGrid.getWidth(); x++) {
if (lGrid.getCell(x,y) == 1) {
g.setColor(Color.red);
g.fillRect(x * lGrid.getSqSize(), y * lGrid.getSqSize(), lGrid.getSqSize(), lGrid.getSqSize());
} else {
g.setColor(Color.white);
g.fillRect(x * lGrid.getSqSize(), y * lGrid.getSqSize(), lGrid.getSqSize(), lGrid.getSqSize());
}
}
}
}
And then another LifeGrid class , which has a method run()that, when called, updates the pixel grid for one generation, and then calls LifeDraw.repaint(). However, if I try to call run()in a loop, the JComponent will not be redrawn until the loop is complete, so all that is ever displayed is the first generation and the last. I figured this was probably updating too fast to redraw, so I tried using Thread.sleep()between iterations, but still had the same problem. Theoretically (or at least I was hoping this is so), it should repaint the component between each iteration and display the pixel animation.
Java, . , , .