Change background of JLabel in runtime using reflection

I need to change background of JLabels dynamically.

I've 70 JLabels in a class. All JLabels represent some specific items. The items names are same as the variable of JLabel. The Sold Items names are saved in database. If I run a query that will return an array of the sold items. The sold items that are same as the JLabel should change the background. Rest will not change.

I've got the variables of all fields like this:

  Field fld[] = BlueLine.class.getDeclaredFields();  
   for (int i = 0; i < fld.length; i++)  
   {
   System.out.println("Variable Name is : " + fld[i].getName());
   }

How can I cast my fld to a JLabel and change background of the JLabel when certain condition meets ? for example:

   if(fld[i] == label5){
   label5.setBackground.(Color.red);
   } // or something like this. ?

Any outline will help.

Jon Skeet
people
quotationmark

Currently you're just looking at the fields themselves - you're interested in the values of those fields. For example:

Object value = fld[i].get(target); // Or null for static fields
if (value == label5) {
    ...
}

Here target is a reference to the object whose fields you want to get the values from. For static fields, just use null, as per the comment.

It's not at all clear that all of this is a good idea, however - problems which can be solved with reflection are often better solved in a different way. We don't really have enough context to advise you of specifics at the moment, but I would recommend that you at least try to think of cleaner designs.

people

See more on this question at Stackoverflow