Lory A Lory A - 14 days ago 9
Java Question

Rotate between colors in String

I'm trying to create a

String
that rotates color. Every letter has a different
color
, and they need to rotate in a linear manner. The text will go inside of a
JLabel
.

I built the text so that it could be created given a word and an array of colors (Strings).

String[] colors = {"white", "blue", "red"};
String word = "foo";
String coloredText;

String[] letters = word.split("(?!^)"); //split text into indiv. letters

coloredText = "<html>";

for(int i = 0, j = 0; i < letters.length; i++, j++){

if(j >= colors.length)
j=0;

coloredText += String.format("<font color='%s'> %s </font>", colors[j], letters[i]);
}

coloredText += "</html>";


This will result in a string that has foo with a white
F
, blue
O
and red final
O
.

Of course if there were less colors than letters, they would just keep on rotating.

Now I have a
timer
to rotate the colors, but I can't figure out the
algorithm
to do it.
Basically, every color should take the place of the following one, with the last one replacing the first.

So for example:

enter image description here

Of course this has to work for any number of given letters and colors, with the colors that don't fit being ignored. (A word of 3 letters with 10 colors will only use the first 3 colors).

I have tried using
.replace()
but
regex
is a bit too difficult for me.

Any idea?

Answer

You can have an additional integer (class or instance variable, depending on your code) as an offset counter between 0 and colors.length-1.

int offset = 0

Every time your timer executes, increment the offset by 1 and check if your offset overflows the allowed offset. If so, reset it to 0.

void onTimerExecutes(){
    offset++;
    if (offset >= colors.length)
        offset = 0;
    applyColorsToText();
}

Then add the offset to your j:

j = offset;
for(int i = 0, i < letters.length; i++, j++)