String instead of jlabel

1

I have an interface with 60 jlabels, named like this: A1 A2 A3 .... A60

The idea is to change the color according to a condition, but I would have to put 60 "if". The idea would be to change the label by means of a string.

The line of code to change the color is this:

Ventana.A2.setForeground(color.GREEN)

But I have the A2 value in a string called "cell", ideally put

Ventana.(celda).setForeground(color.GREEN)

Java does not allow this, any idea of how it is done?

    
asked by juan sanchez 31.03.2018 в 16:39
source

3 answers

1

Try to create an ArrayList of type JLabel, so you can access it by means of the position number

    JLabel[] etiqueta = new JLabel[60];
    ArrayList<JLabel> lista = new ArrayList<>();//Lista de tipo JLabel
    for (int i = 0; i < 10; i++) {
        etiqueta[i] = new JLabel("A" + i);//Inicializas c/u de los JLabel
        lista.add(etiqueta[i]);//Se van agregando a la lista
    }

So that way you can change if you know the position

lista.get(25).setForeground(Color.yellow);//Si conoces la posicion en la lista

Or for a certain range

for (int i = 15; i < 30; i++) {
        lista.get(i).setForeground(Color.yellow);
    }

Or by filtering the search by a given name, for example:

for (int i = 0; i < lista.size(); i++) {
        if (lista.get(i).getName().equals("Ventana")) { //Este se lo asignas con la función .setName y es diferente al nombre que muestra la JLabel
            lista.get(i).setForeground(Color.yellow); 
        }
    }
    
answered by 26.07.2018 в 09:00
1

You can create a Hashmap:

HashMap<String,JLabel> listaLabels = new HashMap<String,JLabel>();
for(int i = 1; i <= 60;i++){
   listaLabels.put("A"+i, new JLabel(""+i));
}

And so to change color of any label you do:

listaLabels.get("A2").setForeground(Color.yellow);

: D.

    
answered by 26.07.2018 в 12:31
0

Juan does not understand much friend, but perhaps the convenient thing would be to use a method in which you pass a label and you call it depending on what you need, example:

public void cambiaColor(Label variable, color tipo){
Ventana.variable.setForeground(tipo);
}
cambiaColor(A2, color.GREEN);

Well, I was impelled by that, God willing, serve you

    
answered by 31.03.2018 в 21:55