Update class fields with sequential names

Asked

Viewed 52 times

1

How to update the background color of 15 JTextField during a loop? For example, I own the following JTextField:

txtEsp1
txtEsp2
txtEsp3
...

And I want to create a loop, to set the background of the 15 as white:

for(int i=1;i<15;i++) {
   txtEsp[i].setBackground(Color.WHITE);
}
  • And what’s the problem?

  • The problem is that the for as it is written in the post does not work, which reason the topic is negative?

  • Then provide a [mcve] with the problem because your doubt does not make any sense with this code.

  • I think you’re looking for Reflection...

1 answer

2


I understand what you are trying to do, but Java does not work like this. When using txtEsp[i], you are referencing a position i to a vector called txtEsp, and not for the name of the variable in question.

To do this, Java offers a feature called Reflection, which allows you to access the class’s own resources. To pick the variables with the name txtEspN it is necessary to use the following function:

public void colorir() {
    for(Field field : getClass().getDeclaredFields()) { // ou ClasseExemplo.class no lugar de getClass()
        if (field.getName().matches("^txtEsp(1[0-5]|[0-9])$")) {
            ((JTextField) field.get(this)).setBackground(Color.WHITE); // ou ClasseExemplo.class no lugar de this
        }
    }
}

In this case, I used the regular expression ^txtEsp(1[0-5]|[1-9])$ to validate the numbers, but you could also validate the numbers after txtEsp with Integer#parseInt() and check if a number is contained in 1 ≤ N ≤ 15.


Note:

When using field.get(this), the compiler can do not find the field searched. This is because Java does not allow the use of local variables such as Fields when searching for them. If this happens, you should turn the local variable into a global variable, placing it in the class scope.

  • There is no setBackground pro package Field type reflect.

  • @Article Thank you, corrected.

  • If you have other fields that meet this condition and are not of the cast type, you will be bursting exception, because your code is taking all fields of the class.

  • 2

    The OP said: "I have the following Jtextfield", and just below has a loop from 1 to 15 for the objects. I suppose there will be errors related to the cast.

  • Note: There is no setBackground pro type lang package object*.

  • At no time did he say that there are jtextfield fields only in the class. It is necessary to treat so that there is no classcastexception.

  • Thanks was just what I was looking for! Articuno, initially I only have the 15 Jtextfield on the screen (It’s a Kanban screen) where I need to clean Kanban every 3 minutes to generate a new.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.