gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:21:54 26 4
gpt4 key购买 nike

我尝试解决这个问题,但我有一个无限循环,不知道如何解决这个问题。引导我。我是 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){}
}
}
}

最佳答案

使用前需要初始化数组:

 int x[] = new int[17];

例如。

关于java - 在Applet中生成随机三角形(动画),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10790682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com