简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM