如何添加可以在我的生命游戏程序中获取生成的功能?

我正在尝试让我的程序在单元格更改其形式的每个步骤中显示(首先在控制台中测试)计数.因此,计数应该从 0 开始,并在每次单元格更改其形式时递增.我试过这个,使用count++但是它不会增加1,而是给我随机数.任何帮助都感激不尽.

导入java.awt.Color;导入 java.util.Timer;导入 java.util.TimerTask;导入 java.awt.Image;导入 java.awt.Graphics;导入 javax.swing.SwingUtilities;公共类 GameOfLife 扩展 javax.swing.JFrame {最终 int wid = 100,hei = 50;公共静态整数计数;boolean[][] currentMove = new boolean[hei][wid], nextMove = new boolean[hei][wid];布尔播放;图像offScrImg;图形offScrGraph;公共 GameOfLife() {初始化组件();offScrImg = createImage(jPanel1.getWidth(), jPanel1.getHeight());offScrGraph = offScrImg.getGraphics();定时器时间 = new Timer();TimerTask 任务 = 新 TimerTask(){公共无效运行(){如果(播放){System.out.println(count);for(int i = 0; i < hei; i++){for(int j = 0; j < wid; j++){nextMove[i][j] = 决定(i,j);}}for(int i = 0; i < hei; i++){for(int j = 0; j < wid; j++){currentMove[i][j] = nextMove[i][j];}}重绘();}}};time.scheduleAtFixedRate(任务, 0, 100);重绘();}私人布尔决定(int i,int j){int 邻居 = 0;//左上角 row-1,col-1if (currentMove[getTopRow(i - 1)][getLeftCol(j - 1)]) 邻居++;//使用 getTopRow 和 getLeftCol 方法确定左上角单元格的索引//左行,col-1if (currentMove[i][getLeftCol(j - 1)]) 邻居++;//左下行+1,col-1if (currentMove[getBottomRow(i + 1)][getLeftCol(j - 1)] ) 邻居++;//底行+1,colif (currentMove[getBottomRow(i + 1)][j]) 邻居++;//右下行+1,col+1if (currentMove[getBottomRow(i + 1)][getRightCol(j + 1)]) 邻居++;//右行,col+1if (currentMove[i][getRightCol(j + 1)]) 邻居++;//右上角 row-1,col+1if (currentMove[getTopRow(i - 1)][getRightCol(j + 1)])neighbors++;//第一行,colif(currentMove[getTopRow(i - 1)][j]) 邻居++;如果(邻居 == 3){计数++;返回真;}if(currentMove[i][j] && 邻居 == 2){计数++;返回真;}返回假;}私人int getLeftCol(int neighbourCol){返回邻居Col <0 ?(wid-1):neighbourCol;//如果leftCol的索引小于0,则使用最右边的col(columns - 1)}私人int getRightCol(int neighbourCol){返回邻居Col >(wid-1) ?0:邻居Col;}私人int getTopRow(int neighbourRow){返回neighbourRow <0 ?(hei - 1):neighbourRow;//如果topRow的索引小于0,则使用底部最后一行(rows - 1)}私人int getBottomRow(int neighbourRow){返回 neighbourRow >(嘿 - 1)?0:邻居行;}私人无效repain(){offScrGraph.setColor(Color.RED);offScrGraph.fillRect(0, 0, jPanel1.getWidth(), jPanel1.getHeight());for(int i = 0 ; i < hei ; i++){for(int j = 0 ; j < wid; j++){如果(当前移动[i][j]){offScrGraph.setColor(Color.GREEN);int x = j * jPanel1.getWidth()/wid;int y = i * jPanel1.getHeight()/hei;offScrGraph.fillRect(x, y, jPanel1.getWidth()/wid, jPanel1.getHeight()/hei);}}}offScrGraph.setColor(Color.BLACK);for(int i = 1; i < hei;i++){int y = i * jPanel1.getHeight()/hei;offScrGraph.drawLine(0, y, jPanel1.getWidth(), y);}for(int j = 1; j < wid;j++){int x = j * jPanel1.getWidth()/wid;offScrGraph.drawLine(x, 0, x, jPanel1.getHeight());}jPanel1.getGraphics().drawImage(offScrImg, 0, 0, jPanel1);}@SuppressWarnings("未选中")//<editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents私人无效initComponents(){jPanel1 = 新 javax.swing.JPanel();jButton1 = new javax.swing.JButton();jButton2 = 新 javax.swing.JButton();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);jPanel1.setBackground(新 java.awt.Color(102, 102, 102));jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {公共无效鼠标拖动(java.awt.event.MouseEvent evt){jPanel1MouseDragged(evt);}});jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {公共无效鼠标点击(java.awt.event.MouseEvent evt){jPanel1MouseClicked(evt);}});jPanel1.addComponentListener(new java.awt.event.ComponentAdapter() {公共无效组件调整(java.awt.event.ComponentEvent evt){jPanel1ComponentResized(evt);}});javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);jPanel1.setLayout(jPanel1Layout);jPanel1Layout.setHorizo​​ntalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 0, Short.MAX_VALUE));jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 293, Short.MAX_VALUE));jButton1.setText("播放");jButton1.addActionListener(new java.awt.event.ActionListener() {公共无效actionPerformed(java.awt.event.ActionEvent evt){jButton1ActionPerformed(evt);}});jButton2.setText("重置");jButton2.addActionListener(new java.awt.event.ActionListener() {公共无效actionPerformed(java.awt.event.ActionEvent evt){jButton2ActionPerformed(evt);}});javax.swing.GroupLayout 布局 = 新 javax.swing.GroupLayout(getContentPane());getContentPane().setLayout(布局);layout.setHorizo​​ntalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jPanel1,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE).addGroup(layout.createSequentialGroup().addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,323,Short.MAX_VALUE).addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))).addContainerGap()));布局.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jPanel1,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jButton1).addComponent(jButton2)).addContainerGap()));盒();}//</editor-fold>//GEN-END:initComponentsprivate void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseClicked}//GEN-LAST:event_jPanel1MouseClickedprivate void jPanel1ComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jPanel1ComponentResizedoffScrImg = createImage(jPanel1.getWidth(), jPanel1.getHeight());offScrGraph = offScrImg.getGraphics();重绘();}//GEN-LAST:event_jPanel1ComponentResizedprivate void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed玩=!玩;if(play) jButton1.setText("暂停");否则 jButton1.setText("播放");重绘();}//GEN-LAST:event_jButton1ActionPerformedprivate void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformedcurrentMove = new boolean[hei][wid];重绘();}//GEN-LAST:event_jButton2ActionPerformedprivate void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseDraggedint j = wid * evt.getX()/jPanel1.getWidth();int i = hei * evt.getY()/jPanel1.getHeight();如果(SwingUtilities.isLeftMouseButton(evt)){currentMove[i][j] = true;} 否则 currentMove[i][j] = false;重绘();}//GEN-LAST:event_jPanel1MouseDragged公共静态无效主要(字符串参数[]){//<editor-fold defaultstate="collapsed" desc="外观设置代码(可选)">/* 如果 Nimbus(Java SE 6 中引入)不可用,则保持默认外观.* 详情见 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html*/尝试 {对于(javax.swing.UIManager.LookAndFeelInfo 信息:javax.swing.UIManager.getInstalledLookAndFeels()){if ("Nimbus".equals(info.getName())) {javax.swing.UIManager.setLookAndFeel(info.getClassName());休息;}}} 捕捉(ClassNotFoundException ex){java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);} 捕捉(实例化异常前){java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);} 捕捉(IllegalAccessException ex){java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);} 捕捉(javax.swing.UnsupportedLookAndFeelException ex){java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);}//</编辑器折叠>java.awt.EventQueue.invokeLater(new Runnable() {公共无效运行(){新的 GameOfLife().setVisible(true);}});}//变量声明 - 不要修改//GEN-BEGIN:variables私有 javax.swing.JButton jButton1;私有 javax.swing.JButton jButton2;私有 javax.swing.JPanel jPanel1;//变量声明结束//GEN-END:variables}

解决方案

使用

import java.awt.*;导入 java.awt.event.*;导入 javax.swing.*;导入 java.util.Random;公共类 GameOfLife 扩展 JPanel {私有 int 行,col;私人布尔isLiving;私有静态int代= 0;公共静态随机随机=新随机();公共GameOfLife(int r,int c){this.row = r;这个.col = c;MouseListener 监听器 = new MouseAdapter() {公共无效鼠标点击(鼠标事件e){isLiving = !isLiving;重绘();}};this.addMouseListener(listener);isLiving = random.nextBoolean();}公共布尔isAlive(int邻居){布尔活=假;如果(this.isLiving){如果(邻居< 2){活着=假;} else if (邻居 == 2 || 邻居 == 3) {活着=真;} else if (neighbors > 3) {活着=假;}} 别的 {如果(邻居== 3){活着=真;}}活着回来;}公共无效setAlive(布尔活着){isLiving = 活着;}公共布尔 isLiving() {返回 this.isLiving;}公共无效paintComponent(图形g){super.paintComponent(g);如果(this.isLiving){g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);} 别的 {g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);}}公共静态无效主要(字符串[]参数){最终整数 s = 40;JPanel ui = new JPanel(new BorderLayout(4, 4));final JLabel generationLabel = new JLabel("0", JLabel.CENTER);ui.add(generationLabel, BorderLayout.PAGE_START);最终的 GameOfLife[][] 生物圈 = 新的 GameOfLife[s][s];final JPanel gui = new JPanel(new GridLayout(s, s, 2, 2));ui.add(gui);for (int ii = 0; ii < s; ii++) {for (int jj = 0; jj < s; jj++) {GameOfLife 细胞 = 新的 GameOfLife(ii, jj);cell.setPreferredSize(新维度(10, 10));gui.add(单元格);生物圈[ii][jj] = 细胞;}}ActionListener al = new ActionListener() {公共无效actionPerformed(ActionEvent ae){boolean[][] living = new boolean[s][s];for (int ii = 0; ii < s; ii++) {for (int jj = 0; jj < s; jj++) {int top = (jj > 0 ? jj - 1 : s - 1);int btm = (jj 

I'm trying to make my program display (testing in console first) the count number at each step where the cell changes its form. So the count should start from 0 and increment each time the cell changes its form. I tried this, using count++ however it doesn't increment by 1 but instead gives me random numbers. Any help will be much appreciated.

import java.awt.Color;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Image;
import java.awt.Graphics;
import javax.swing.SwingUtilities;

public class GameOfLife extends javax.swing.JFrame {

final int wid = 100, hei = 50;
public static int count;
boolean[][] currentMove = new boolean[hei][wid], nextMove = new boolean[hei][wid];
boolean play;
Image offScrImg;
Graphics offScrGraph;

public GameOfLife() {
    initComponents();
    offScrImg = createImage(jPanel1.getWidth(), jPanel1.getHeight());
    offScrGraph = offScrImg.getGraphics();
    Timer time = new Timer();
    TimerTask task = new TimerTask(){
        public void run(){
            if(play){
                System.out.println(count);
                for(int i = 0; i < hei; i++){
                    for(int j = 0; j < wid; j++){
                        nextMove[i][j] = decide(i,j);

                    }
                }
                for(int i = 0; i < hei; i++){
                    for(int j = 0; j < wid; j++){
                        currentMove[i][j] = nextMove[i][j];

                    }
                }
                repain();
            }
        }
    };
    time.scheduleAtFixedRate(task, 0, 100);
    repain();
}

private boolean decide(int i, int j){
    int neighbors = 0;

    // top-left row-1,col-1

    if (currentMove[getTopRow(i - 1)][getLeftCol(j - 1)]) neighbors++;  //Uses getTopRow and getLeftCol methods to determine the indices of the top left cell

    // left row,col-1
    if (currentMove[i][getLeftCol(j - 1)]) neighbors++;

    // bottom left row+1,col-1
    if (currentMove[getBottomRow(i + 1)][getLeftCol(j - 1)] ) neighbors++;

    // bottom row+1,col
    if (currentMove[getBottomRow(i + 1)][j]) neighbors++;

    // bottom right row+1,col+1
    if (currentMove[getBottomRow(i + 1)][getRightCol(j + 1)]) neighbors++;

    // right row,col+1
    if (currentMove[i][getRightCol(j + 1)]) neighbors++;

    // top-right row-1,col+1
    if (currentMove[getTopRow(i - 1)][getRightCol(j + 1)])neighbors++;

    // top row-1, col
    if(currentMove[getTopRow(i - 1)][j]) neighbors++;


    if(neighbors == 3) {       
        count++;
        return true;                
    }
    if(currentMove[i][j] && neighbors == 2){   
        count++;
        return true;         
    }
    return false;
}
private int getLeftCol(int neighbourCol) {
    return neighbourCol < 0 ? (wid-1) : neighbourCol;   //If the index of leftCol is less than 0, it uses the right most col (columns - 1)
}

private int getRightCol(int neighbourCol) {
    return neighbourCol > (wid-1) ? 0 : neighbourCol;
}

private int getTopRow(int neighbourRow) {
    return neighbourRow < 0 ? (hei - 1) : neighbourRow; //If the index of topRow is less than 0, it uses the bottom last row (rows - 1)
}

private int getBottomRow(int neighbourRow) {
    return neighbourRow > (hei - 1) ? 0 : neighbourRow;
}

private void repain(){
    offScrGraph.setColor(Color.RED);
    offScrGraph.fillRect(0, 0, jPanel1.getWidth(), jPanel1.getHeight());
    for(int i = 0 ; i < hei ; i++){
        for(int j = 0 ; j < wid; j++){
            if(currentMove[i][j]){
                offScrGraph.setColor(Color.GREEN);
                int x = j * jPanel1.getWidth()/wid;
                int y = i * jPanel1.getHeight()/hei;
                offScrGraph.fillRect(x, y, jPanel1.getWidth()/wid, jPanel1.getHeight()/hei);
            }
        }
    }
    offScrGraph.setColor(Color.BLACK);
    for(int i = 1; i < hei;i++){
        int y = i * jPanel1.getHeight()/hei;
        offScrGraph.drawLine(0, y, jPanel1.getWidth(), y);
    }
    for(int j = 1; j < wid;j++){
        int x = j * jPanel1.getWidth()/wid;
        offScrGraph.drawLine(x, 0, x, jPanel1.getHeight());
    }
    jPanel1.getGraphics().drawImage(offScrImg, 0, 0, jPanel1);
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setBackground(new java.awt.Color(102, 102, 102));
    jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseDragged(java.awt.event.MouseEvent evt) {
            jPanel1MouseDragged(evt);
        }
    });
    jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jPanel1MouseClicked(evt);
        }
    });
    jPanel1.addComponentListener(new java.awt.event.ComponentAdapter() {
        public void componentResized(java.awt.event.ComponentEvent evt) {
            jPanel1ComponentResized(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
            );
    jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 293, Short.MAX_VALUE)
            );

    jButton1.setText("Play");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jButton2.setText("Reset");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 323, Short.MAX_VALUE)
                                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap())
            );
    layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jButton2))
                    .addContainerGap())
            );

    pack();
}// </editor-fold>//GEN-END:initComponents

private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseClicked

}//GEN-LAST:event_jPanel1MouseClicked

private void jPanel1ComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jPanel1ComponentResized
    offScrImg = createImage(jPanel1.getWidth(), jPanel1.getHeight());
    offScrGraph = offScrImg.getGraphics();
    repain();
}//GEN-LAST:event_jPanel1ComponentResized

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    play = !play;
    if(play) jButton1.setText("Pause");
    else jButton1.setText("Play");
    repain();
}//GEN-LAST:event_jButton1ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    currentMove = new boolean[hei][wid];
    repain();
}//GEN-LAST:event_jButton2ActionPerformed

private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseDragged
    int j = wid * evt.getX() / jPanel1.getWidth();
    int i = hei * evt.getY() / jPanel1.getHeight();
    if(SwingUtilities.isLeftMouseButton(evt)){
        currentMove[i][j] = true;
    }else currentMove[i][j] = false;
    repain();
}//GEN-LAST:event_jPanel1MouseDragged

public static void main(String args[]) {
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(GameOfLife.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new GameOfLife().setVisible(true);
        }
    });
}

// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}

解决方案

This is how it can be done using a related code example.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

public class GameOfLife extends JPanel {

    private int row, col;
    private boolean isLiving;
    private static int generation = 0;

    public static Random random = new Random();

    public GameOfLife(int r, int c) {
        this.row = r;
        this.col = c;
        MouseListener listener = new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                isLiving = !isLiving;
                repaint();
            }
        };
        this.addMouseListener(listener);
        isLiving = random.nextBoolean();
    }

    public boolean isAlive(int neighbors) {
        boolean alive = false;
        if (this.isLiving) {
            if (neighbors < 2) {
                alive = false;
            } else if (neighbors == 2 || neighbors == 3) {
                alive = true;
            } else if (neighbors > 3) {
                alive = false;
            }
        } else {
            if (neighbors == 3) {
                alive = true;
            }
        }
        return alive;
    }

    public void setAlive(boolean alive) {
        isLiving = alive;
    }

    public boolean isLiving() {
        return this.isLiving;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (this.isLiving) {
            g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
        } else {
            g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
        }
    }

    public static void main(String[] args) {
        final int s = 40;
        JPanel ui = new JPanel(new BorderLayout(4, 4));
        final JLabel generationLabel = new JLabel("0", JLabel.CENTER);
        ui.add(generationLabel, BorderLayout.PAGE_START);

        final GameOfLife[][] biosphere = new GameOfLife[s][s];
        final JPanel gui = new JPanel(new GridLayout(s, s, 2, 2));
        ui.add(gui);
        for (int ii = 0; ii < s; ii++) {
            for (int jj = 0; jj < s; jj++) {
                GameOfLife cell = new GameOfLife(ii, jj);
                cell.setPreferredSize(new Dimension(10, 10));
                gui.add(cell);
                biosphere[ii][jj] = cell;
            }
        }

        ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                boolean[][] living = new boolean[s][s];
                for (int ii = 0; ii < s; ii++) {
                    for (int jj = 0; jj < s; jj++) {
                        int top = (jj > 0 ? jj - 1 : s - 1);
                        int btm = (jj < s - 1 ? jj + 1 : 0);
                        int lft = (ii > 0 ? ii - 1 : s - 1);
                        int rgt = (ii < s - 1 ? ii + 1 : 0);
                        int neighbors = 0;
                        if (biosphere[ii][top].isLiving()) {
                            neighbors++;
                        }
                        if (biosphere[ii][btm].isLiving()) {
                            neighbors++;
                        }
                        if (biosphere[lft][top].isLiving()) {
                            neighbors++;
                        }
                        if (biosphere[lft][btm].isLiving()) {
                            neighbors++;
                        }
                        if (biosphere[lft][jj].isLiving()) {
                            neighbors++;
                        }
                        if (biosphere[rgt][jj].isLiving()) {
                            neighbors++;
                        }
                        if (biosphere[rgt][top].isLiving()) {
                            neighbors++;
                        }
                        if (biosphere[rgt][btm].isLiving()) {
                            neighbors++;
                        }
                        living[ii][jj] = biosphere[ii][jj].isAlive(neighbors);
                    }
                }
                for (int ii = 0; ii < s; ii++) {
                    for (int jj = 0; jj < s; jj++) {
                        biosphere[ii][jj].setAlive(living[ii][jj]);
                    }
                }
                generationLabel.setText("Generation: " + generation++);
                gui.repaint();
            }
        };

        Timer timer = new Timer(50, al);
        timer.start();

        JOptionPane.showMessageDialog(null, ui);
        timer.stop();
    }
}

相关文章