import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.Console;
import java.util.Scanner;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class CA extends JComponent{
int[] cells;
int[] ruleset;
int w = 10;
int generation = 0;
int width = 600; //Pixel length of the window
private BufferedImage caImage;
CA()
{
cells = new int[width/w];
//Rule 90 of Wolfram
ruleset = new int[]{0,1,0,1,1,0,1,0};
for (int i = 0; i < cells.length; i++)
cells[i] = 0;
cells[cells.length/2] = 1;
print(cells, cells.length);
generate();
}
public void generate()
{
int [] nextgen = new int[cells.length];
while(generation<6)
{
for(int i=1; i<cells.length-1; i++)
{
int left = cells[i-1];
int middle = cells[i];
int right = cells[i+1];
nextgen[i] = rules(left, middle, right);
}
cells = nextgen;
print(cells, cells.length);
System.out.println();
paintComponent(this.getGraphics());
generation++;
}
}
public void print(int[] a, int length)
{
System.out.println();
for(int i=0; i<length; i++)
{
System.out.print(a[i]+" ");
}
}
public int rules(int a, int b, int c)
{
String s = ""+a+b+c;
int index = Integer.parseInt(s, 2);
return ruleset[index];
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for(int i=0; i<cells.length; i++)
{
if(cells[i] == 0)
{
Color color = Color.WHITE;
g2.setColor(color);
}
else if(cells[i] == 1)
{
Color color = Color.BLACK;
g2.setColor(color);
}
//Rectangle rect = new Rectangle(i*w, generation*2, w, w);
//g2.fill(rect);
g2.drawRect(i*w, generation*2, w, w);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame();
frame.setSize(600, 600);
frame.setTitle("Cellular Automaton");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.RED);
frame.setVisible(true);
//Scanner input = new Scanner(System.in);
//String pause = input.nextLine();
CA cellularAutomaton = new CA();
frame.add(cellularAutomaton);
frame.setVisible(true);
}
}
我想通过从 60 个元素的一维数组中获取 1 或 0 来显示 10x10 像素的白色或黑色矩形。我对一维数组的不同更新元素重复相同的操作 6 次。(实现元胞自动机)。
问题:当我想在 600x600 的窗口上显示结果时出现问题。该g2.setColor(Color)
行抛出一个NullPointerException
. 我找不到发生此错误的原因。