1

Could anybody help with the component gradual color changing. I want color to be changed for

new Color(255,0,0)  

to

new Color(0,0,0)  

tried different variants with timers, but get stuck. And btw is it right way to do this with timers?

Thanks in advance!

mr.nothing
  • 5,141
  • 10
  • 53
  • 77
  • 1
    Hadn't you heard of [JLayer](http://docs.oracle.com/javase/tutorial/uiswing/misc/jlayer.html) yet ? :-) – nIcE cOw May 11 '12 at 09:30
  • @nIcEcOw As OP is planning to go with your suggestion (read from his comment on an answer), its nice to post it as an answer :-) – COD3BOY May 11 '12 at 09:54
  • @Sanjay : Am I suppose to write a single word ? I could've given that as an answer, though as @@PerryMonschau , in his answer had done some hard work, and a one word answer is what my conscious is not allowing me. So I am confused :( but the one who can provide one example too, on the given lines can surely post this as an answer. – nIcE cOw May 11 '12 at 10:14
  • @nIcEcOw apart from consciousness, consider the future visitors to this question, they will miss a good answer :) – COD3BOY May 11 '12 at 10:28

2 Answers2

4

Something along these lines:

Color before = new Color(255,0,0);
Color after = new Color(0,0,0);
Color current = before;
int maxtime = 1000;
int step = 0;

public void step()
{
    if(step == maxtime)
        return;
    step++;
    double percentComplete = step/maxtime;
    double percentGone = 1-percentComplete;
    int red = (int)(before.getRed()*percentGone+after.getRed()*percentComplete);
    int green = (int)(before.getGreen()*percentGone+after.getGreen()*percentComplete);
    int blue = (int)(before.getBlue()*percentGone+after.getBlue()*percentComplete);
    int alpha = (int)(before.getAlpha()*percentGone+after.getAlpha()*percentComplete);
    current = new Color(red, green, blue, alpha);
    //set component's color to current
}

Note, you may need to do some checks to make sure red green and blue don't exceed 255, but I'm not yet sure.

(this function should belong to the component whose color you're changing, you should call this on each timer tick)

Perry Monschau
  • 883
  • 8
  • 22
4

Please do consider using JLayer as an alternative for your quest :-)

nIcE cOw
  • 24,468
  • 7
  • 50
  • 143