TulsaNewbie
TulsaNewbie

Reputation: 401

How can I use a string as a variable?

Here's the situation: I have a program that needs to dynamically assign color using the statement

mb.setForeground(Color.????);

where ???? is normally RED or GREEN or what have you. But, since I do not know until runtime what is going to go into that value, I need to pass that information using a string:

String fColorTxt = "????";

So, the value that fColorTxt is assigned to is the value I want to end up after Color.

I have now done the following, but I have no idea if it's going to work...

public enum ColorChoice {
    BLACK   (  0,   0,   0),
    BLUE    (  0,   0, 255), LIGHT_BLUE    (  0, 128, 255), DARK_BLUE    (  0,   0, 128),
    BROWN   (160,  96,   0), LIGHT_BROWN   (208, 144,   0), DARK_BROWN   ( 96,  32,   0),
    CYAN    (  0, 255, 255), LIGHT_CYAN    (176, 255, 255), DARK_CYAN    (  0, 139, 139),
    GRAY    (128, 128, 128), LIGHT_GRAY    (211, 211, 211), DARK_GRAY    ( 64,  64,  64),
    GREY    (128, 128, 128), LIGHT_GREY    (211, 211, 211), DARK_GREY    ( 64,  64,  64),
    GREEN   (  0, 255,   0), LIGHT_GREEN   (128, 255, 128), DARK_GREEN   (  0, 128,   0),
    MAGENTA (255,   0, 255), LIGHT_MAGENTA (255, 144, 255), DARK_MAGENTA (144,   0, 144),
    MINT    ( 96, 221,  96), LIGHT_MINT    (208, 238, 208), DARK_MINT    ( 16, 187,  16),
    ORANGE  (255, 128,   0), LIGHT_ORANGE  (255, 176,  48), DARK_ORANGE  (192,  64,   0),
    PINK    (255, 192, 203), LIGHT_PINK    (255, 128, 255), DARK_PINK    (231,  84, 128),
    YELLOW  (255, 255,   0), LIGHT_YELLOW  (255, 255, 128), DARK_YELLOW  (160, 160,   0),
    WHITE   (255, 255, 255);

    private int iRed;
    private int iGreen;
    private int iBlue;

    ColorChoice(int iRed, int iGreen, int iBlue) {
        this.iRed   = iRed;
        this.iGreen = iGreen;
        this.iBlue  = iBlue;
    }

}

I guess I need to figure out how to do a few things. I ultimately would love to be able to just call a function like so:

 sColor = myFunction(fColorTxt);
 mb.setForeground(sColor);
 sColor = myFunction(bColorTxt);
 mb.setBackground(sColor);

where bColorTxt and fColorTxt are dynamically set at runtime using variables, and sColor is of the Color type.

(The below may still be true, but obviously I've written the names into my enum so it is no longer necessary):

(Only in some cases. I want to use 8 of java's original predefined colors, and then I defined another 20 or so of my own that I will have to figure out how to handle putting them in; e.g.:

Color myDarkYellow   = new Color (160, 160,   0);

and then

if (fColorTxt == "DARK_YELLOW") { fColor = myDarkYellow; }
mb.setForeground(fColor);

Does that look right or is there a better way to handle that?)

Upvotes: 0

Views: 53

Answers (1)

Clément Audry
Clément Audry

Reputation: 56

Maybe you could use Enum for avoid the 28 else if

Upvotes: 1

Related Questions