java - 当循环卡住程序时继续计算并在计算之间暂停

标签 java

你好,我有这段代码,你可以点击几个立方体将它们设置为死或活,然后根据一组规则,java将计算下一步后哪些单元格将是活的/死的。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
class GameOfLife implements ActionListener{
Scanner scanner;                                                               //to      read the text file
File file;
boolean play = false;
String filename = "birth.txt";                                                 //the file that has to be read
Cell[][] cells=new Cell[10][10];                                               //array containing all the cells
JButton nextButton;
JButton playButton;
JPanel buttonPanel;
JPanel cellPanel;
GridLayout gridLayout=new GridLayout(10,10);
JFrame frame=new JFrame();
void buildit(){
    readInput();
    frame.setSize(600,700);        
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    buttonPanel=new JPanel();
    buttonPanel.setPreferredSize(new Dimension(600,100));
    frame.add(buttonPanel, BorderLayout.PAGE_START);
    nextButton=new JButton("Next generation");
    playButton=new JButton("Play");
    nextButton.setPreferredSize(new Dimension(150,50));
    playButton.setPreferredSize(new Dimension(150,50));
    nextButton.addActionListener(this);
    playButton.addActionListener(this);
    frame.add(nextButton, BorderLayout.LINE_START);
    frame.add(playButton, BorderLayout.LINE_END);

    cellPanel=new JPanel();        
    cellPanel.setLayout(gridLayout);                                               //gives the panel a gridlayout
    cellPanel.setPreferredSize(new Dimension(600,600));
    frame.add(cellPanel, BorderLayout.PAGE_START);
    for(int i=0; i<100; i++){  
        cells[i%10][i/10]=new Cell();                                            //i/10 will be rounded down, so it equals the rownumber
        cellPanel.add(cells[i%10][i/10]);
        cells[i%10][i/10].addMouseListener(cells[i%10][i/10]);                   //add a mouselistener to the cell
        cells[i%10][i/10].setOpaque(true);                                       //makes the backgroundcolor visible
        cells[i%10][i/10].setBackground(Color.BLACK);
        cells[i%10][i/10].setBorder(BorderFactory.createLineBorder(Color.WHITE));

    }    

    frame.setVisible(true);
    for(int i=0; i<100; i++){  
        for(int j=0; j<9; j++){
            if((i%10-1+j%3>=0) && (i%10-1+j%3<10) && (i/10-1+j/3>=0) && (i/10-1+j/3<10) && !(j==4)){   //exclude cells that are outside the frame (non existant) and the cell itself  
                cells[i%10][i/10].setNeighbours(cells[i%10-1+j%3][i/10-1+j/3]);           //this adds all the neighbours to the arraylist
            }
        }
    }
}
public void actionPerformed(ActionEvent e){
    if(e.getSource()==nextButton){
        for(int i=0; i<100; i++){ 
            cells[i%10][i/10].calculateNextState(); 
        }
        for(int i=0; i<100; i++){  
            cells[i%10][i/10].updateToNextState();
        }
    }
    else{if (e.getSource()==playButton) {
      play = true;
      for (int p=0; p<3;p++) {

        for(int i=0; i<100; i++){ 
            cells[i%10][i/10].calculateNextState(); 
        }
        for(int i=0; i<100; i++){  
            cells[i%10][i/10].updateToNextState();
        }

    }

    }

    }
}

void readInput(){
    try{
        file = new File( filename);
        scanner = new Scanner( file );
        String nextGen="";                                                               //this string will contain the output
        int row=scanner.nextInt();                                                       //read the row number
        int col=scanner.nextInt();                                                       //and the column number
        Cell[][] cellen=new Cell[row][col];                                              //array containing all the cells
        for(int i=0; i<row*col; i++){
            cellen[i%row][i/col]=new Cell(); 
            if(scanner.next().equals(".")){
                cellen[i%row][i/col].setState(CellState.alive);                                     //set the state
            }
            else{
                cellen[i%row][i/col].setState(CellState.dead); 

            }

        }
        for(int i=0; i<row*col; i++){
            for(int j=0; j<9; j++){
                if((i%row-1+j%3>=0) && (i%row-1+j%3<row) && (i/col-1+j/3>=0) && (i/col-1+j/3<col) && !(j==4)){ 
                    cellen[i%row][i/col].setNeighbours(cellen[i%row-1+j%3][i/col-1+j/3]);            //set the neighbours
                }
            }
        }
        for(int i=0; i<row*col; i++){
            cellen[i%row][i/col].calculateNextState();                                  //calculate the next state for all the cells
        }
        for(int i=0; i<row*col; i++){
            cellen[i%row][i/col].updateToNextState();                                   //update all the cells to the next state
        }
        for(int i=0; i<row; i++){
            for(int j=0; j<col; j++){
                if(cellen[i%row][i/col].getCurrentState()==CellState.alive){                             //the cell is alive if getCurrentState is true
                    nextGen+="*";
                }
                else{
                    nextGen+=".";
                }
            }
            nextGen+=System.getProperty("line.separator");                              //add an enter after each row
        }
        System.out.println(nextGen);                                                    //print the next generation to the console
    }

    catch(FileNotFoundException e) {
        System.out.println( "Could not find or open file <"+filename+">\n"+e );         
    } 
}
public static void main(String[] args) {
    new GameOfLife().buildit();
}
}

我的问题是,当我尝试无限次地保持计算时 我的程序卡住了,如下面的代码所示

 else{if (e.getSource()==playButton) {
      play = true;
      for (int p=0; p<3;p++) {

        for(int i=0; i<100; i++){ 
            cells[i%10][i/10].calculateNextState(); 
        }
        for(int i=0; i<100; i++){  
            cells[i%10][i/10].updateToNextState();
        }

    }

    }

我只进行了 3 次计算,但我希望它能够无限次地进行计算,直到出现停止按钮(要创建喷射流),每次计算之间有 1 秒的暂停。我已经尝试过 while 循环,但这只是卡住了我的应用程序 对于暂停和无限计算的一些帮助将非常感激

最佳答案

这里的问题是您的代码正在 Swing Event Dispatch Thread 中运行,这意味着您正在做的所有事情都必须先完成,然后才能返回到响应按钮单击和绘图更改等操作。

我建议你研究一下:

关于java - 当循环卡住程序时继续计算并在计算之间暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19553533/

相关文章:

java - Flink 没有向 kafka 提交偏移量

使用 JAXB 将 Java 转换为 XML

java - 如何在IntelliJ中调用getter setter模板中的方法?

java - 如何在 Java 的交互式命令行过程中输入值?

java - 为什么 Controller 代码没有在 spring boot 应用程序中执行

java - Math.random() 如何用于数据分布?

java - 有什么理由在 Web 上使用 Java 而不是 Django/Python、PHP 等?

java - com.mysql.jdbc.MysqlDataTruncation : Data truncation: Incorrect datetime value: 'Mon Feb 11 00:00:00 IST 2013' for column 'INVOICE_DATE' at row 1

java - 访问与工作目录相同级别的 .properties 文件

java - 避免在对 JButton 执行操作后卡住