Creating several Sequentially Named Labels(Java/Swing)

Elmo187

Limp Gawd
Joined
Jun 7, 2003
Messages
291
I'm trying to make a 10x10 "grid" of labels, with each label in each row named sequentially.

eg.
A1 A2 A3 A4.....
B1 B2 B3 B4.....
C1 C2 C3 C4....

Here is the code that I tried for creating the first row:

Code:
for (int i=1;i<=10;i++)
{
      JLabel Ai = new JLabel();
      Ai.setOpaque(true);
      Ai.setBackground(Color.blue);
      Ai.setPreferredSize(new Dimension(GRID_WIDTH,GRID_HEIGHT));
      Ai.setBorder(new LineBorder(Color.black, 1));
      gameBoard.add(Ai);
}

But this, as I discovered, does not insert the value of 'i' into the variable name. You guys have any suggestions on how to go about this?
 
can you make an array of JLabels? maybe
Code:
JLabel[][] myLabels = new JLabel[10][10];
for (int i=0; i<10; i++) {
    for (int j=0; j<10; j++) {
        myLabels[i][j] = new JLabel();
        myLabels[i][j].setOpaque(true);
        ...
    }
}
i'm not sure of the exact syntax of creating an array of a class type. i've only taken computer science 1 in java so we haven't really don anything like that, only int/double/String arrays. but i'm sure using an array is the key
 
EDIT: I went back to reread the problem and realized the array solution is what the author was after. I'm sorry for confusion. I've cut the rest of my post as it was not relevent.
 
As a rule of thumb, having varibly named variables is _never_ a good idea.

The array's a good place to start.

The other thing you should do is look at the available constructors for JLabel . This one looks promising :

Code:
JLabel(String text) 
          Creates a JLabel instance with the specified text.



The rest should be trivial.
 
Thanks for the suggestions, the Array solution looks to be the thing to do.

Ameoba: That constructor actually just sets the text on the label at creation, but thanks for the suggestion. :)
 
Back
Top