NicholasLong
NicholasLong

Reputation: 13

How do I set up a method that sets the text of multiple JLabels?

cannonCounter1.setText(cannonAccu1 + "/" + cannonMax);
cannonCounter2.setText(cannonAccu2 + "/" + cannonMax);
cannonCounter3.setText(cannonAccu3 + "/" + cannonMax);
cannonCounter4.setText(cannonAccu4 + "/" + cannonMax);
cannonCounter5.setText(cannonAccu5 + "/" + cannonMax);
cannonCounter6.setText(cannonAccu6 + "/" + cannonMax);

I'm trying to set up a method that shortens these lines of code. The only difference between each line is the counter variable name changes, and the accumulator variable name changes. I would just leave it because it works but as my program expands there will be around 500-1000 of these lines that are almost exactly the same. I am trying to create a method but have no idea how to get the method to set the text for multiple JLabels!! Any ideas, or will I just have to leave it?

Upvotes: 1

Views: 49

Answers (1)

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

Create an array of JLabels and loop over it.

JLabel[] labels = new JLabel[6];
for (int i = 0 ; i < labels.length ; i++)
    labels[i].setText(yourtext);

Of course, each index should contain a JLabel before the loop. This is just an example.

Upvotes: 3

Related Questions