本人新手,想把走过的坐标导入数组中出现这问题!球大侠指导
出现的问题:Exception in thread "Thread-2" java.lang.NullPointerException
at suiji$PaintThread.run(suiji.java:61)
at java.lang.Thread.run(Thread.java:619)
源码(此程序需导入图片,/* */我没去掉,去掉后为错误的程序)
import javax.swing.*;
import java.awt.*;
import java.io.*;
import javax.imageio.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.lang.Math;
public class suiji extends JFrame {
public void init() {
JFrame f = new JFrame("0000");
f.setBounds(0, 0,1200,650);
f.setLayout(null);
PaintThread jpanel = new PaintThread();
Thread t=new Thread(jpanel);
t.start();
GridLayout grid = new GridLayout(30,30);
jpanel.setLayout(grid);
jpanel.setBounds(0,0,1200,650);
f.add(jpanel);
f.setResizable(true);
f.setVisible(true);
f.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public int getPixel(int x,int y) throws AWTException{ Robot rb
= new Robot();
Rectangle rec = new Rectangle(0,0,100,100);
BufferedImage bi = rb.createScreenCapture(rec);
int pixelColor = bi.getRGB(x, y);
return pixelColor;
}
public static void main(String args[]) {
{
suiji tankwar = new suiji();
tankwar.init();
}
}
class PaintThread extends JPanel implements Runnable {
int x =220, y =230,n=1,i,k=0,x1=220,y1=220,x3=1100,y3=600;
double a=3;
final ImageIcon imageIcon = new ImageIcon("aa.jpg");
Image image = imageIcon.getImage();
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image,0,0,this);
g.drawRect(x,y,0,0);
g.fillOval(x, y, 30, 30);
g.drawRect(0,0,x3,y3);
}
public void run() {
try {
/*
int a1,b1;
int [][]shuzu=new int[x3][];
{
for(a1=1;a1<x3;a1++)
for(b1=1;b1<y3;b1++)
shuzu[a1][b1]=0;
}*/
BufferedImage bi = ImageIO.read(new File("aa.jpg"));
do{ for(i=0;i<=120;i++)
{n=bi.getRGB((int)(Math.cos(i*Math.PI/60-Math.PI/2)*15+x+15),(int)
(Math.sin(i*Math.PI/60-Math.PI/2)*15+y+15));
if(n==-16777216){System.out.print(n);
if(i>=30&&i<=60||i>90&&i<=120)
k=(i+30+(int)(Math.random()*30));
else k=(i-30-(int)(Math.random()*30)); break;}}
x=(int)(Math.cos(k*Math.PI/60-Math.PI/2)*2+x);
y=(int)(Math.sin(k*Math.PI/60-Math.PI/2)*2+y);
/*shuzu[x][y]+=1;
if(shuzu[x][y]==2)
break;*/
System.out.print("x="+x1);System.out.println(" y="+y1);
repaint();
try{Thread.sleep(10);}
catch(InterruptedException e){e.printStackTrace();}
}while(true);
} catch (IOException e)
{e.printStackTrace();}}
}
} --------------------编程问答-------------------- shuzu只定义了行,没有定义列;所以下面赋值的时候,报空针指异常。
赋值前,给shuzu[a1]先定义长度:
for (a1 = 1; a1 < x3; a1++) {
shuzu[a1] = new int[y3];
for (b1 = 1; b1 < y3; b1++) {
shuzu[a1][b1] = 0;
}
}
至于下标从0还是从1开始,及数组长度,按自己需要,但要注意不要数组越界
补充:Java , Java相关