简体   繁体   English

在Applet中生成随机三角形(动画)

[英]Generating random Triangles in Applet (Animation)

I try to solve this question, but I have an infinite loop and don't know how to solve this problem. 我尝试解决此问题,但是我遇到了无限循环,并且不知道如何解决此问题。 Guide me. 引导我。 I'm new in Java. 我是Java新手。

In terminal: 在终端:

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)

Thanks for HELP! 感谢帮助!

Question: Write an applet that displays randomly generated triangles in different colors. 问题:编写一个小程序,以不同的颜色显示随机生成的三角形。

    /////////////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){} 
        }       
    }
}

You need to initialize your arrays before usage: 您需要在使用前初始化数组:

 int x[] = new int[17];

for example. 例如。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM