2016-10-18 12 views
1

現在、私は "Game of Life"のバージョンを作成する課題を抱えています。しかし、私の細胞は現れません。Game of Life - Javaは動作しません(セルは表示されません)

これは私のセルクラスです:

class Cell{ 
boolean alive; //true if cell is alive, false if cell is dead 
int numNeighbors; //number of alive neightboring cells 

//change alive/dead state of the cell 
void setAlive(boolean state){ 
    alive = state; 
} 

//return alive/dead state of the cell 
boolean isAlive(){ 
    return alive; 
} 

//set numNeightbors of the cell to n 
void setNumNeighbors(int n){ 
    numNeighbors = n; 
} 

//take the cell to the next generation 
void update(){ 
    if(numNeighbors <2 || numNeighbors >3){ 
     alive = false; 
    } else if((numNeighbors == 2 || numNeighbors == 3) && alive == true){ 
     alive = true; 
    } else if(numNeighbors == 3 && alive == false){ 
     alive = true; 
    } 
} 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    g.setColor(Color.blue); 
    g.setOpaque(true); 
    for(int i = 0; i < row; i++){ 
     for(int j = 0; j < col; j++){ 
      if(grid[i][j].isAlive()){ 
       g.setColor(Color.BLACK); 
      } else { 
       g.setColor (Color.WHITE); 
       g.fillRect(50, 50, 50*i, 50*j); 
      } 
     } 
    } 
} 

そして、これは私は誰もがこのプログラムを動作させるために私を助けることを願って、私のGameOfLifeクラス

<pre>import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import javax.swing.*; 
import java.io.*; 


public class GameOfLife implements MouseListener{ 
Cell[][] grid; //contain grid of cells 
String birthFilename = "birth.txt"; //text file where initial generation is stored 
int row; //number of rows 
int col; //number of columns 


ActionListener actionListener = new ActionListener(){ 
    javax.swing.Timer timer = new javax.swing.Timer(500, this); //new timer 

    @Override 
    public void actionPerformed(ActionEvent event){ 
    } 
}; 

public void buildIt() { 
    int width = 600; 
    int height = 600; 
    JFrame frame = new JFrame("Game of Life"); 
    readInitial(); 

    //adds button interface 
    JPanel buttonbar = new JPanel(); 
    frame.add(buttonbar, BorderLayout.SOUTH); 
    JButton start = new JButton("Start"); 
    JButton stop = new JButton("Stop"); 
    JButton nextg = new JButton("Next Generation"); 
    buttonbar.add(nextg); 
    buttonbar.add(start); 
    buttonbar.add(stop); 

    JPanel panel = new JPanel(); 
    frame.add(panel); 
    panel.setPreferredSize(new Dimension(width, height)); 
    panel.setLayout(new GridLayout(row, col, 4, 4)); 
    frame.pack(); 
    frame.setBackground(Color.WHITE); 
    frame.setVisible(true); 


} 

public void mousePressed(MouseEvent e) { 
//add code to update x and y 
} 
public void mouseReleased(MouseEvent e) { } 
public void mouseClicked(MouseEvent e) { } 
public void mouseEntered(MouseEvent e) { } 
public void mouseExited(MouseEvent e) { } 


//calculate number of living neightbors of each cell and sets numNeighbors 
//Does not update dead/live state of cells 
void calculateNumNeighbors(){ 
    int numNeighbors = 0; 
    for(int i = 1; i < row + 1; i++){ 
     for(int j = 1; j < col + 1; j++){ 
      for(int k = -1; k < 2; k++){ 
       for(int m = -1; m < 2; m++){ 
        if(grid[i+k][j+m].isAlive() && !(k == 0 && m == 0)){ 
         numNeighbors++; 
        } 
       } 
      } 
      grid[i][j].setNumNeighbors(numNeighbors); 
     } 
    } 
} 

//create grid and read initial generation from file 
void readInitial(){ 
    try{ 
     grid = new Cell[row + 2][col + 2]; //empty neighbors at corners, so + 2 
     File file = new File(birthFilename); 
     Scanner scanner = new Scanner(file); 
     row = scanner.nextInt(); 
     col = scanner.nextInt(); 

     for(int i = 0; i < row + 2; i++){ 
      for (int j = 0; j < col + 2; j++){ 
       grid[i][j] = new Cell(); 
      } 
     } 

     for(int i = 1; i < row + 1; i++){ 
      for (int j = 1; j < col + 1; j++){ 
       if(scanner.next().equals(".")){ 
        grid[i][j].setAlive(false); 
       } else if(scanner.next().equals("*")){ 
        grid[i][j].setAlive(true); 
       } 
      } 
     } 

     for(int i = 0; i < row + 2; i++){ 
      grid[0][i].setAlive(false); 
      grid[row+2][i].setAlive(false); 
     } 
     for(int j = 0; j < col + 2; j++){ 
      grid[j][0].setAlive(false); 
      grid[j][col+2].setAlive(false); 
     } 

    } catch(FileNotFoundException e) { 
     grid = new Cell[12][12]; 
     row = 10; 
     col = 10; 
     for(int i = 0; i < 12; i++){ 
      for (int j = 0; j < 12; j++){ 
       grid[i][j] = new Cell(); 
       grid[i][j].setAlive(false); 
      } 
     } 
    } 
} 



//update grid to the next generation, using the values of numNeightbors in the cells 
void nextGeneration(){ 
    for(int i = 1; i < row + 1; i++){ 
     for (int j = 1; j < col + 1; j++){ 
      grid[i][j].update(); 
     } 
    } 
} 


public static void main(String[] arg) { 
    (new GameOfLife()).buildIt();  
} 

です。

+0

は何も表示されない:それはまた、メインプログラムは、それがクリックされたかどうかを決定するために、そののMouseListenerに使用することができますpublic boolean contains(Point p)方法を持っていますか? –

+0

コンパイルされません: 'super.paintComponent(g)' – AJNeufeld

+0

SwingUtilities.invokeLater(Runnable)でイベントディスパッチスレッドを起動したことはありません。 –

答えて

5

私は何かを描くべきではありません。はい、paintComponentメソッドを持つCellクラスがありますが、このメソッドはSwingコンポーネントの一部ではないので無意味です。描画を行うJPanelは何もしません。 Cellクラスの他の問題も、単一のセルだけでなく、グリッド全体を描画しようとしているようです。

  • はそれを、それは自分自身を描画することができますpublic void draw(Graphics g)方法を与える
  • 代わりに、セルのpaintComponentメソッドを取り除きます。
  • セルのグリッドを保持するJPanelを作成します。
  • このJPanelに、paintComponentのオーバーライドで図面を表示させますか? forループ内に保持されているすべてのCellのメソッドdraw(g)を呼び出します。
  • 常に@Overrideアノテーションをオーバーライドされたメソッドの上に配置します。この作業をpaintComponentの上に行っていた場合、コンパイラは何かが間違っていると警告していました。たとえば、

は:ここは生命のゲームをしない小さなプログラムですが、非コンポーネントセルのグリッドを保持し、表示のJPanelの一例を示しています。 「非コンポーネント」では、SimpleCellクラスはSwingコンポーネントから継承されず、Swingメソッドはありませんが、上記のようにdraw(...)メソッドがあり、これを使用して自身を描画できます。

import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import javax.swing.*; 

@SuppressWarnings("serial") 
public class SimpleCellGrid extends JPanel { 
    private static final int ROWS = 40; 
    private static final int COLS = 40; 
    private static final int CELL_WIDTH = 10; 
    private static final int PREF_W = CELL_WIDTH * COLS; 
    private static final int PREF_H = CELL_WIDTH * ROWS; 
    private SimpleCell[][] cellGrid = new SimpleCell[ROWS][COLS]; 

    public SimpleCellGrid() { 
     MyMouse myMouse = new MyMouse(); 
     addMouseListener(myMouse); 
     for (int row = 0; row < cellGrid.length; row++) { 
      for (int col = 0; col < cellGrid[row].length; col++) { 
       int x = col * CELL_WIDTH; 
       int y = row * CELL_WIDTH; 
       cellGrid[row][col] = new SimpleCell(x, y, CELL_WIDTH); 
      } 
     } 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D) g; 
     for (SimpleCell[] cellRow : cellGrid) { 
      for (SimpleCell simpleCell : cellRow) { 
       simpleCell.draw(g2); 
      } 
     } 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     if (isPreferredSizeSet()) { 
      return super.getPreferredSize(); 
     } 
     return new Dimension(PREF_W, PREF_H); 
    } 

    private class MyMouse extends MouseAdapter { 
     @Override 
     public void mousePressed(MouseEvent e) { 
      for (SimpleCell[] cellRow : cellGrid) { 
       for (SimpleCell simpleCell : cellRow) { 
        if (simpleCell.contains(e.getPoint())) { 
         simpleCell.setAlive(!simpleCell.isAlive()); 
        } 
       } 
      } 
      repaint(); 
     } 
    } 

    private static void createAndShowGui() { 
     JFrame frame = new JFrame("SimpleCellGrid"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(new SimpleCellGrid()); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(() -> createAndShowGui()); 
    } 
} 

import java.awt.Color; 
import java.awt.Graphics2D; 
import java.awt.Point; 
import java.awt.Rectangle; 

public class SimpleCell { 
    private static final Color CELL_COLOR = Color.RED; 
    private boolean alive = false; 
    private int x; 
    private int y; 
    private int width; 
    private Rectangle rectangle; 

    public SimpleCell(int x, int y, int width) { 
     this.x = x; 
     this.y = y; 
     this.width = width; 
     rectangle = new Rectangle(x, y, width, width); 
    } 

    public boolean isAlive() { 
     return alive; 
    } 

    public void setAlive(boolean alive) { 
     this.alive = alive; 
    } 

    public void draw(Graphics2D g2) { 
     if (alive) { 
      g2.setColor(CELL_COLOR); 
      g2.fill(rectangle); 
     } 
    } 

    public boolean contains(Point p) { 
     return rectangle.contains(p); 
    } 

    @Override 
    public String toString() { 
     return "SimpleCell [alive=" + alive + ", x=" + x + ", y=" + y + ", width=" + width + ", rectangle=" + rectangle 
       + "]"; 
    } 

} 
関連する問題