1

So to be specific i have a two-dimensional array filled with JLabels. If from another method i get one JLabel that we know for sure that exists in that array how can i get the coordinates of the label in the array. part of code is this(P.S The array is [9][5]):

    labelsArrayColumns[1][1] = jLabel11;
    labelsArrayColumns[2][1] = jLabel21;
    labelsArrayColumns[3][1] = jLabel31;
    labelsArrayColumns[4][1] = jLabel41;
    labelsArrayColumns[5][1] = jLabel51;
    labelsArrayColumns[6][1] = jLabel61;
    labelsArrayColumns[7][1] = jLabel71;
    labelsArrayColumns[8][1] = jLabel81;
    labelsArrayColumns[9][1] = jLabel91;

So if I have jLabel81 how can i find out in which position of the array it is? And we are expecting [8][1].

Sir. Hedgehog
  • 1,260
  • 3
  • 17
  • 40

1 Answers1

1

I'd suggest two ways:
1) work through the whole 2D-array and compare every element with labelsArrayColumns[i][j].equals(jLabel81) until you find it
2) override the JLabel Class: just add a method to save and retrieve the position of the JLabel within your array

  • 1
    so you mean something like this, correct? @Benjamin Kalloch `public JLabelcheckTheArray(JLabel actionLabel){ for(int i = 1; i < 9; i++){ for(int j = 1; j < 5; j++){ if(labelsArrayColumns[i][j].equals(actionLabel)){ return labelsArrayColumns[i][j]; } } } return null; }` – Sir. Hedgehog May 01 '13 at 18:33
  • 1
    well, yes, that's my 1st suggestion. But your example would return the particular object (which I thought you already know?). As you want to know the position I'd declare i and j outside the loops so their values can be read after you found the object: `int i, j; outerloop: for(i=0;i<9;i++){ for(j=0;j<5;j++) if(labelsArrayColumns[i][j].equals(actionLabel) break outerloop; }` – Benjamin Kalloch May 01 '13 at 19:42
  • 1
    but only if it finds the label will return it, otherwise it will continue looking for it, and it will return it one way or another because it exists so it will find it.... actually there is no reason to use "break outerloop;" – Sir. Hedgehog May 01 '13 at 19:55
  • 1
    I'm not sure what do you mean? To break a nested loop you need `break outerloop;`, don't you? Otherwise you'll just skip the inner loop. And you have to break the loops otherwise i and j both will always be 9 | 5 at the end. – Benjamin Kalloch May 01 '13 at 20:04
  • 1
    But as long as it is like that: `if(labelsArrayColumns[i][j].equals(actionLabel)){ return labelsArrayColumns[i][j]; }` Then at the same time that it will be equal it will return it without changing values correct? – Sir. Hedgehog May 01 '13 at 23:13
  • 1
    Ah, ok, i see. Yes, that's right, but then the function exits and the values for i and j are also lost, unless they are declared globally as instance members. – Benjamin Kalloch May 02 '13 at 15:07