I understand what you're trying to do, but Java does not work like this. When using txtEsp[i]
, you are referencing a i
position for a vector named txtEsp
, not the name of the variable in question.
To do this, Java offers a feature called Reflection, which allows you to access resources of the class itself. To get the variables named txtEspN
you need 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 it is a number is contained in 1 ≤ N ≤ 15
.
Note:
When using field.get(this)
, the compiler can not find the searched field. This is because Java does not allow the use of local variables like Fields when looking for them. If this happens, you should make the local variable global by putting it in the class scope.