您好我正在尝试创建一个applet,其中包含带有学生信息的矩形。这是我目前的代码:
public void paint(Graphics g)//makes pretty pictures
{
**Student grade = new Student();**
for(int a = 0; a<arr.length;a++){
for(int b =0; b<arr[a].length;b++){
g.drawRect(165*a+5,55*b+5,150,50);
**String grades = grade.toString();**
**g.drawString(grades,160*a+5,60*b+5);**
}
}
repaint();
}
class Student
{
private int test1, test2, test3, avg, ID;
public Student()
{
test1=(int)(Math.random()*51+50);
test2=(int)(Math.random()*51+50);
test3=(int)(Math.random()*51+50);
avg=(test1+test2+test3)/3;
ID=(int)(Math.random()*90000+10000);
}
public int test1(){ return test1;}
public int test2(){ return test2;}
public int test3(){ return test3;}
public int avg(){ return avg;}
public int ID(){ return ID;}
public String toString(){ return "ID:"+ID+" Avg: "+avg;}
}
在paint方法中,我希望显示与生成的矩形相同数量的Student类。但是,它只是打印出一个无限循环。 谢谢你的帮助!
答案 0 :(得分:1)
请勿在{{1}}方法中致电repaint
。
paint
表示“此组件需要重新绘制”。如果你从repaint()
打电话,那么每当它被绘制时,它都会得到另一个绘画本身的请求。所以它将继续绘画和绘画。
也许您没有意识到您正在重写paint(Graphics)
方法,该方法决定了组件的呈现方式。
答案 1 :(得分:0)
你看过Student
班了吗?
其test1
,test2
和test3
字段是在实例时随机生成的。
相关代码如下所示,可在Student
:
test1=(int)(Math.random()*51+50);
test2=(int)(Math.random()*51+50);
test3=(int)(Math.random()*51+50);
avg=(test1+test2+test3)/3;
ID=(int)(Math.random()*90000+10000);
Math.random()
生成0到1之间的随机数,因此Math.random()*51+50
将生成50(0 * 51 + 50)到101(1 * 51 + 50)之间的随机数,Math.random()*90000+10000
1}} 10000到100000之间的随机数
平均值显然也会发生变化,因为它基于test1
,test2
和test3
字段。