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个元素的1D数组中获取1或0来显示10x10像素的白色或黑色矩形。对于1D阵列的不同更新元素,我重复相同的操作6次。 (实施细胞自动机)。
问题:
当我想在600x600的窗口上显示结果时,会出现此问题。 g2.setColor(Color)
行抛出NullPointerException
。我找不到发生此错误的原因。
答案 0 :(得分:4)
您的Graphics对象为null。不要在组件上调用getGraphics()
来获取Graphics实例,因为它不会持久存在。可以在BufferedImage上调用它,但如果从组件中获取它,那么任何重绘都会变为null。而是使用JVM在paintComponent(...)
方法参数中提供的Graphics实例或BufferedImage中的Graphics实例。
另外,请勿直接致电paintComponent(...)
。那是JVM的工作。
另外,你的while循环不起作用,因为它会占用并锁定Swing Event Dispatch Thread或EDT。您应该使用SwingWorker在后台线程上生成BufferedImage,然后显示在Swing事件线程上创建的Image。