我正在编写一个程序,显示10个随机颜色和随机位置的框,但根据任务,“屏幕上只显示最后10个随机框。也就是说,在绘制第11个框时,删除所绘制的第一个框。在绘制第12个框时,删除第二个框,以此类推。”
我不知道如何做到这一点,因为我能得到的最远是使用for循环来显示10个随机框。
到目前为止,这就是我所拥有的:
package acm.graphics;
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class ShootingStar extends GraphicsProgram
{
public void run()
{
final int width = 800;
final int height = 600;
final int boxWidth = 50;
final int maxBoxes = 10;
this.setSize(width, height);
Random random = new Random();
for( int i = 0; i<=maxBoxes ;i++) {
float r = random.nextFloat();
float b = random.nextFloat();
float g = random.nextFloat();
Color randColor = new Color(r,g,b);
GRect r1 = new GRect(boxWidth, boxWidth);
r1.setFilled(true);
r1.setColor(randColor);
GPoint x = new GPoint(random.nextInt(width),
random.nextInt(height));
add(r1, x);
}
this.pause(100);
}
}如有任何建议或建议,将不胜感激。
发布于 2013-11-12 04:04:52
这样做的一种方法是:
public class Test {
private int boxWidth, boxHeight = 50;
private GRect[] rects;
private int first;//keep track of oldest rectangle
public Test()
{
this.rects = new GRect[10];
this.first = 0;
}
void drawRects()
{
//for each rectangle, draw it
}
void addRect()
{
this.rects[first] = new GRect(boxWidth, boxHeight);
first++;
first = first % 10; //keeps it within 0-9 range
}
}只要在需要添加新矩形时调用addRect(),新矩形就会取代最老的矩形。
发布于 2013-11-12 01:53:29
你只重复了十次,这就成了十个盒子,对吗?我们从那开始吧。maxBoxes应该大于10 (我不知道你想做什么,所以我不能说maxBoxes应该是什么)
基本上,您想要将这些框的信息存储在某个地方,然后将最后十项提取出来。为此,您可以使用数组。如果你要推到主数组的末尾,那么你只需要弹出最后的十个,然后画出盒子。
https://stackoverflow.com/questions/19919393
复制相似问题