Search code examples
javaswingjlabel

How to formulate multiple JLabels that all will follow same procedure?


I am working with 100 JLabels aligned in a grid format. 10 x 10.

Each JLabel has a number associated with it. Depending on the value of the number, the JLabel's background will be set. Therefore, an intensity map. The value number are in the same class file, on a different tab (a 10x10 table with numbers).

My concern is that it would take forever to do something like this:

Private JLabel first one....last 100th one

first one = new JLabel("") if(first one value is value is 5) {setBackground color Red} else if {blue} else if {green}

And so one till the last 100th one.


Solution

  • You're going to want to use an array and a loop to initialize them.

    JLabel[][] labels = new JLabel[10][10];
    for (int i = 0; i < 10; ++i) {
      for (int j = 0; j < 10; ++j) {
        labels[i][j] = new JLabel("");
        //Do whatever with it here
      }
    }