java随时间改变颜色的RGB值
我的程序标题屏幕有一个背景,希望它的颜色随着时间慢慢改变。背景是这样绘制的:
g.setColor(255, 0, 0);
g.fillRect(0, 0, 640, 480); //g is the Graphics Object
所以现在背景是红色的。我想让它慢慢褪为绿色,然后是蓝色,然后再回到红色。我试过:
int red = 255;
int green = 0;
int blue = 0;
long timer = System.nanoTime();
long elapsed = (System.nanoTime() - timer) / 1000000;
if(elapsed > 100) {
red--;
green++;
blue++;
}
g.setColor(red, green, blue);
g.fillRect(0, 0, 640, 480);
我确实有更多的代码来实现它,所以如果任何一个值达到0,它们将被加上,如果它们达到255,它们将被减去,但你明白了。这是一种渲染方法,每秒调用60次。(计时器变量是在render方法之外创建的)
谢谢
# 1 楼答案
使用swing Timer按顺序设置新的背景色。为了计算新的颜色,你可以使用
Color.HSBtoRGB()
,每次定时器被激活时改变色调成分# 2 楼答案
正如kiheru所建议的,你应该使用定时器
下面是一个例子
当您运行此功能时,它将每秒更改面板背景颜色(我使用的是随机颜色)