简体   繁体   中英

Java use a variable as another variable

So here is the deal. I do not want to write 50+ if statements or switches if possible.

Setup: I have a Main class that is a GUI. In that GUI I have a JLabel in which I want to change its background color.

It has been initialized as a static JLabel so it can be set by other classes and this is working fine.

Main class

 goodornot.setBackground(Color.LIGHT_GRAY);

in another class that is taking input from a script I want to setup variables that are generic.

PerfLoop class

RunChecks.rcMin = 50;
RunChecks.rcMax = 75;
RunChecks.changeColor = "goodornot";
String[] one = linecut.split("="); <-- I am splitting a string IGNORE
RunChecks.rcToCheck = Integer.parseInt(one[1]);
RunChecks rc = new RunChecks();
new Thread(rc).start();

So I set all that up and it looks great and no errors.

now in another class (runChecks) I am trying to pull in the tree variables as are so they can be drop in universal variables, but I am having one issue.

RunChecks class

public void run() {
        // TODO Auto-generated method stub
        if (rcToCheck <= rcMin){
            Main.changeColor.setBackground(Color.GREEN);
        } else if (){
        }

I cannot use changeColor here to set the color of goodornot. How can I get the variable changeColor to represent what needs to go into Main.(right here).setBackground(Color.GREEN)?

I think there is a way but for the life of me I tried a bunch of different ways and no go.

yes all variables are setup as static strings and int.

thanks

You're starting a new thread, so you need a reference to your label. Try the following:

class RunChecks implements Runnable
{
    private JLabel label;

    public RunChecks(JLabel label)
    {
        this.label = label;
    }

    public void run()
    {
        if (rcToCheck <= rcMin){
            label.setBackground(Color.GREEN);
        } else if (){
        }
    }
}

...

    RunChecks rc = new RunChecks(yourLabelVariableHere);
    new Thread(rc).start();

If I understand the problem, here's one approach:

Set up a collection of JLabels, for example:

static HashMap<String,JLabel> labels;

which is populated with all your labels. Then you can reference these labels dynamically by key:

labels.get("**changeColor**").setBackground(Color.GREEN);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM