2013-07-15 57 views
0

我有我的程序的標題屏幕的背景,並希望它的顏色隨着時間慢慢變化。這是如何繪製背景:更改隨着時間的推移顏色的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次的渲染方法。 (計時器變量是在渲染方法之外創建的)

謝謝!

+0

你嘗試過什麼實現這一目標? – Makky

+0

@Makky我剛剛在。 – sparklyllama

+0

中加入了它是不是工作呢? – Makky

回答

0

使用擺動Timer來設置新的背景顏色。爲了計算新顏色,您可以使用Color.HSBtoRGB(),每次激活定時器時更改色調分量。

0

正如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); 
    } 
} 
+0

雖然技術上正確,這個答案違反了Swing的單線程規則。請閱讀[The Event Dispatching](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html)以獲取更多詳細信息 – MadProgrammer

+0

感謝@MadProgrammer我會牢記這一點。 – Makky

相關問題