0

I have a timer that's fading a color from white to black, but I'm having some issues.

I have an array of ints to represent the RGB values.

I have a timer which runs every 100ms and decrements the RGB value in the array.

The problem I'm having is that I will end up with other colors in the middle, green yellow, red, etc.

What I am trying to do is to fade from white to black, so I need the color to become a different shade of grey as the timer runs.

Iswanto San
  • 18,263
  • 13
  • 58
  • 79

1 Answers1

0

Declare a global variable and call it fading.

Color fading = Color.white;

In your timer's body:

if(fading.getRed()>0){
    fading = new Color(fading.getRed()-1,fading.getGreen()-1,fading.getBlue()-1);
    //do whatever you have to do with your fading color
}

Everytime your timer executes this code it will decrease the RGB value from white to black.

The result:

LOOP NO | COLOR
       1: R=255, G=255, B=255
       2: R=254, G=254, B=254
       3: R=253, G=253, B=253
       4: R=252, G=252, B=252
       5: R=251, G=251, B=251
       6: R=250, G=250, B=250
        .
        .
        .
     255: R=0,   G=0,   B=0

EDIT

Example:

import java.awt.Color;

public Class YourClass{

    Color fading = Color.white;

    public YourClass(){
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (fading.getRed() > 0) {
                    fading = new Color(fading.getRed() - 1, fading.getGreen() - 1, fading.getBlue() - 1);
                    //do other stuff here
                }
            }
        };

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(task, 0, 100);
    }
}
BackSlash
  • 21,927
  • 22
  • 96
  • 136
  • Thank you! I kept wondering how to change each of the RGB values. This worked. –  Apr 20 '13 at 21:17