有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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方法之外创建的)

谢谢


共 (2) 个答案

  1. # 1 楼答案

    使用swing Timer按顺序设置新的背景色。为了计算新的颜色,你可以使用Color.HSBtoRGB(),每次定时器被激活时改变色调成分

  2. # 2 楼答案

    正如kiheru所建议的,你应该使用定时器

    下面是一个例子

    当您运行此功能时,它将每秒更改面板背景颜色(我使用的是随机颜色)

    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);
        }
    }