String instead of jlabel


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:


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


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

asked by juan sanchez 31.03.2018 в 16:39

3 answers


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++) {

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
answered by 26.07.2018 в 09:00

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:


: D.

answered by 26.07.2018 в 12:31

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){
cambiaColor(A2, color.GREEN);

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

answered by 31.03.2018 в 21:55