Update fields of a class with sequential names

0

How to update the background color of 15 JTextField during a loop? For example, I have 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);
}
    
asked by anonymous 29.11.2017 / 14:15

2 answers

1

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.

    
29.11.2017 / 17:11
-1

You could define the fields in a vector (or list if the quantity varies):

JTextField[] txtEsp = new JTextField[15];
for (int i = 0; i < txtField.length; i++) {
    txtEsp[i] = new JTextField();
    // configuração do JTExtField
}

this way it avoids the need to use Reflection; the loop to set the color is almost like the question:

for(int i=0; i<txtEsp.length; i++) {
    txtEsp[i].setBackground(Color.WHITE);
}

And there's also the possibility of getting all the sub-components of a graphical component (depending on the way the GUI was built):

// assumindo que (só) os campos txtEspXX foram adicionados ao panel
for (Component comp : panel.getComponents) {
    if (comp instanceof JTextField) {
        comp.setBackground(Color.WHITE);
    }
}
    
29.11.2017 / 22:25