随时间更改颜色的RGB值

时间:2013-07-15 10:30:29

标签: java colors

我的程序标题屏幕背景,并希望它的颜色随着时间的推移慢慢变化。这就是背景的绘制方式:

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次。 (timer变量是在render方法之外创建的)

谢谢!

2 个答案:

答案 0 :(得分:0)

使用摆动Timer定期设置新的背景颜色。要计算新颜色,您可以使用Color.HSBtoRGB(),每次激活计时器时更改色调组件。

答案 1 :(得分:0)

根据kiheru的建议,你应该使用Timer。

这是一个例子。

当你运行它时,它会每秒更改面板背景颜色(我使用的是随机颜色)

import java.awt.Color;
import java.awt.EventQueue;
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestColor {

    private JFrame frame;
    private JPanel panel;
    private Timer timer;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TestColor window = new TestColor();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public TestColor() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {

        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        panel = new JPanel();
        panel.setBounds(23, 61, 354, 144);
        frame.getContentPane().add(panel);
        timer = new Timer();
        TimerClass claa = new TimerClass();
        timer.scheduleAtFixedRate(claa, new Date(), 1000);
    }

    private class TimerClass extends TimerTask {

        @Override
        public void run() {

            panel.setBackground(randomColor());

        }

    }

    public Color randomColor() {
        Random random = new Random(); // Probably really put this somewhere
                                        // where it gets executed only once
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        return new Color(red, green, blue);
    }
}
相关问题