摆动计时器如何工作?
您好,我在尝试理解摇摆计时器时遇到了麻烦.为了帮助我,有人可以给我看一个简单的闪烁动画吗?我在互联网上四处寻找,但仍然不完全了解它们是如何工作的.如果有人能给我一个这样的例子,那就太有帮助了:
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
然后使用该颜色进行绘制:
And then use that color to draw with:
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 教程.
相关文章