How to manipulate Labels using a loop

Asked

Viewed 412 times

1

How can I use these Abels using a loop instead of creating 40 lines of repeated code?

jLabel1.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(1)+".png")));
jLabel2.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(1)+".png")));
jLabel3.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(2)+".png")));
jLabel4.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(3)+".png")));
  • why in English? (mistake?)

  • @Earendul The question was in English and I translated, I just forgot to comment here, sorry. Maybe his difficulty is in catching the object jLabel + i, but since I don’t know java I can’t opine on that...

  • 1

    I think it was a CTRL+C, CTRL+V kind of rushed. Look: Loop using jLabels in swing.

  • no, first I put it here, then I saw it was in the Portuguese section. the control+C went from here to here. First day, first post....

1 answer

2


Rodrigo,

you can create a jLabel vector:

JLabel [ ] labels = new JLabel [40];
for (int i=0; i < labels.length; i++){
   labels[i] = new JLabel ( );
   //Todo o codigo que voce precisar que aqui.
}
  • I didn’t want to create new Labels, as I’m using swing, I created the layout already with the 40 Labels

  • Rodrigo, I think it might be easier for you to modify the declaration form of your 40 Abels. In order to modify your attributes without having to replicate the 40 lines. The same way you replicated in the declaration. Or, assign your already declared Abels to a vector position. Type labels[0] = jLabel1; labels[1] = jLabel2;

  • @Rodrigocipriano you actually created a vector of Labels references variables, Jlabel’s objects will not be created at the end of the line JLabel [] labels = new JLabel [40];. If you don’t give one new for each of these reference variables you will come across a NullPointerException when trying to access them. That is, the answer is right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.