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.
And what’s the problem?
– user28595
The problem is that the for as it is written in the post does not work, which reason the topic is negative?
– Matheus Arruda
Then provide a [mcve] with the problem because your doubt does not make any sense with this code.
– user28595
I think you’re looking for Reflection...
– Mateus