我有一个算法,我已经实现了填充任何形状...但它立即填充形状没有任何延迟...我希望它显示一种动画,以便可以看到洪水如何填充当形状被填充时算法起作用。
这是我的算法:
public static void floodFill(BufferedImage image, int x,int y, int fillColor)
{
java.util.ArrayList<Point> examList=new java.util.ArrayList<Point>();
int initialColor=image.getRGB(x,y);
examList.add(new Point(x,y));
while (examList.size()>0)
{
Point p = examList.remove(0); // get and remove the first point in the list
if (image.getRGB(p.x,p.y)==initialColor)
{
x = p.x; y = p.y;
image.setRGB(x, y, fillColor); // fill current pixel
examList.add(new Point(x-1,y));
examList.add(new Point(x+1,y));
examList.add(new Point(x,y-1));
examList.add(new Point(x,y+1));
}
}
}
启动计时器应该放在哪里?
最佳答案
基本上,您需要某种方法来等待指定的时间段,然后执行更新。
在像 Swing 这样的 GUI 框架中工作时,您不能简单地在 UI 线程上 hibernate ,因为这会阻止 UI 线程保持屏幕最新。同样,在该方法存在之前,UI 线程也无法处理绘制请求。
如果没有更多上下文,您可以做一些“类似”的事情...
public static void floodFill(final BufferedImage image, int x, int y, final int fillColor) {
final java.util.ArrayList<Point> examList = new java.util.ArrayList<Point>();
final int initialColor = image.getRGB(x, y);
examList.add(new Point(x, y));
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!examList.isEmpty()) {
Point p = examList.remove(0); // get and remove the first point in the list
if (image.getRGB(p.x, p.y) == initialColor) {
int x = p.x;
int y = p.y;
image.setRGB(x, y, fillColor); // fill current pixel
examList.add(new Point(x - 1, y));
examList.add(new Point(x + 1, y));
examList.add(new Point(x, y - 1));
examList.add(new Point(x, y + 1));
}
repaint(); // Assuming your painting the results to the screen
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.start();
}
它使用 javax.swing.Timer
来安排重复的回调(在本例中,每 40 毫秒),处理列表中的下一个元素,这实际上充当了一种延迟循环
参见How to use Swing Timers了解更多详情
关于java - 用于动画填充多边形的洪水的 Swing 计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035266/