我的类中的函数在测试后工作。 ColorDrop会创建指定颜色的下降滴。指定速度的SpeedDrop等等。 我想把我的滴放在一个列表中,在GUI中批量生成它们。 Drop是超类,ColorDrop和SpeedDrop是扩展超类的子类。 代码编译,但GUI是空白的。我是不是把我的数组列表错了?还是我不正确地调用该列表中的对象的方法?类型超类的Arraylist可容纳不同的子类型
package advancedobject;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.ArrayList;
public class MyGooDrop extends Goo {
Drop testDrop;
Drop colorDrop;
Drop fastDrop;
Drop wavyDrop;
int random = (int) Math.random()*width;
ArrayList<Drop> drops;
public MyGooDrop()
{
testDrop = new Drop(width/2, -10, 10);
colorDrop = new ColorDrop(width/3, -10, 10, Color.BLUE);
fastDrop = new SpeedDrop ((width * 3/4), -10, 10, 5);
wavyDrop = new WavyDrop (-10, height/2, 10);
drops = new ArrayList<Drop>();
fillDropList();
}
public void fillDropList()
{
for(int i = 0; i<= 12; i++)
{
if (i <= 4)
drops.add(i, new Drop ((int) Math.random()*width, -10, 10));
else if (i>4 && i<=8)
drops.add(i, new ColorDrop ((int) Math.random()*width, -10, 10, Color.BLUE)); //drops.get(i).randomPainter()
else
drops.add(i, new SpeedDrop ((int) Math.random()*width, -10, 10, (int) Math.random()*10));
}
}
public void draw(Graphics2D g) {
// Fill background
g.setColor(Color.GRAY);
g.fillRect(0, 0, width, height);
testDrop.draw(g);
colorDrop.draw(g);
fastDrop.draw(g);
wavyDrop.draw(g);
for(int i = 0; i<=12; i++)
drops.get(i).draw(g);
}
public void update(){
testDrop.move(width, height);
colorDrop.move(width, height);
fastDrop.move(width, height);
wavyDrop.move(width, height);
for(int i = 0; i<=12; i++)
drops.get(i).move(width, height);
}
public static void main(String[] args) {
MyGooDrop tester = new MyGooDrop();
tester.go();
}
}
添加到列表时,您不需要强制转换为“拖放”,因为您添加的所有项都继承它 – fge
如果没有强制转换,它不起作用:\ –
转换为“拖放”是完全不必要的。 – Yuushi