摇摆计时器如何工作? [英] how does a swing timer work?

查看:207
本文介绍了摇摆计时器如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我在试图理解挥杆计时器时遇到了麻烦。帮助我可以有人给我看一个简单的闪烁动画?我在网上看了很多但仍然不完全明白他们是如何工作的。如果有人能给我一个这样的例子会很有帮助:

hello i am having trouble trying to understand swing timers. to help me could someone show me a simple flickering animation? i have looked arround on the internet but still dont fully understand how they work. it would be so helpful if someone could give me an example like this:

如果我创建了一个圆圈:

say if i created a circle:

g.setColor(colors.ORANGE);
g.fillOval(160, 70, 50, 50);

我怎么能使用摇摆计时器将颜色从橙色改为使用摇摆计时器的灰色有延迟吗?

how could i then use a swing timer to change the color from orange to say Gray using a swing timer with a delay?

非常感谢你帮助我理解:)

thank you so much for helping me understand :)

推荐答案

首先,你不会硬编码你的颜色使用如下:

First of all, you wouldn't hard-code your color use like this:

g.setColor(colors.ORANGE);
g.fillOval(160, 70, 50, 50);

因为这会阻止所有改变颜色状态的能力。而是使用类字段来保存使用的颜色,并将其称为类似 ovalColor

Since this prevents all ability to change the color's state. Instead use a class field to hold the Color used, and call it something like ovalColor:

private Color ovalColor = SOME_DEFAULT_COLOR; // some starting color

然后使用该颜色绘制:

g.setColor(ovalColor);
g.fillOval(160, 70, 50, 50);

然后我给我的班级数组Color或 ArrayList< Color> ; 和一个int索引字段:

I'd then give my class an array of Color or ArrayList<Color> and an int index field:

private static final Color[] COLORS = {Color.black, Color.blue, Color.red, 
       Color.orange, Color.cyan};
private int index = 0;
private Color ovalColor = COLORS[index]; // one way to set starting value

然后在Swing Timer的ActionListener中我会增加索引,我用数组或ArrayList的大小来修改它,我得到索引指示的颜色并调用 repaint();

Then in the Swing Timer's ActionListener I'd increment the index, I'd mod it by the size of the array or of the ArrayList, I'd get the Color indicated by the index and call repaint();

index++;
index %= COLORS.length;
ovalColor = COLORS[index];
repaint();

另外这里有一个类似的例子

另外请查看 Swing Timer教程

这篇关于摇摆计时器如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆