Referencing a Java Control with a String

6

I have a array string with the names of controls Label and I want to reference them by that name. Or what is the same, I want to pass a String to a control Label . For example, in VBA it would be like this:

for i=0 to 10
 formulario.Controls(miarray(i)).setcaption = "" 
next i

But, how do I do it in Java?

    
asked by Argus 01.04.2017 в 19:21
source

1 answer

6

To achieve this purpose, it is necessary to obtain the Component that have your Container , as you only want to manipulate the JLabel you would have to verify that the Component is of JLabel , this is done by the operator instanceof , if this is fulfilled it would be valid to validate that the name of the component is within your Array of Names.

String [] nombres = new String[]{"label1","label4","label3"}; /* Array de Nombres*/
Component[] componentes = JFrame.getContentPane().getComponents();/* Obtenemos 
                                                                   los componentes*/
  for (int i=0; i < componentes.length; i++) {
     if (componentes[i] instanceof JLabel) { /* Verificamos el Tipo de Componente*/
        /* Verificamos si el nombre existe en el Arreglo de Nombres*/
         boolean x = Arrays.asList(nombres).contains(componentes[i].getName());
         /* Si Existe entonces aplicas los cambios necesarios ,
            en este caso se cambio el Texto */
         if(x)((JLabel)componentes[i]).setText("Nuevo Texto");
      }
 }
    
answered by 01.04.2017 / 20:24
source