0

我试图解决这个问题,但我有一个无限循环,不知道如何解决这个问题。引导我。我是 Java 新手。

在终端:

Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
        at ThreadApplet.RandGen(ThreadApplet.java:10)
        at ThreadApplet.paint(ThreadApplet.java:30)
        at java.awt.Container.update(Container.java:1988)
        at sun.awt.RepaintArea.updateComponent(RepaintArea.java:255)

感谢帮助!

问题:编写一个小程序,以不同颜色显示随机生成的三角形。

    /////////////Applet

import java.awt.*;

import java.applet.*;

public class ThreadApplet extends Applet{
    MyThread thread;
    int x[],y[];
    public boolean ctrl=true;

    public void RandGen(){
        for (int i=0; i<3;i++){
            x[i]=(int)Math.random()*100;
            y[i]=(int)Math.random()*100;
        }       
    }

    public void start(){
        if (thread==null){
            thread = new MyThread(this);
            thread.start();
        }
    }

    public void stop(){
        thread = null;
    }

    public void paint(Graphics g){
        if (ctrl==true){
            g.setColor(Color.blue);
        } else {
            g.setColor(Color.red);
        }
        RandGen();
        g.fillPolygon(x,y,3);   
    }
}

public class MyThread extends Thread{
    ThreadApplet applet;

    public MyThread (ThreadApplet applet){
        this.applet=applet;
    }
    public void run(){
        Thread thisThread = Thread.currentThread();
        while (this==thisThread){           
            applet.repaint();
            try{Thread.sleep(50);}
            catch(InterruptedException e){} 
        }       
    }
}
4

1 回答 1

3

您需要在使用前初始化数组:

 int x[] = new int[17];

例如。

于 2012-05-28T21:42:01.100 回答