简体   繁体   English

如何设置设置多个JLabel文本的方法?

[英]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. 我会离开它,因为它可以工作,但随着我的程序扩展,将有大约500-1000这些线几乎完全相同。 I am trying to create a method but have no idea how to get the method to set the text for multiple JLabels !! 我正在尝试创建一个方法,但不知道如何获取方法来设置多个JLabels的文本! Any ideas, or will I just have to leave it? 任何想法,还是我只需要离开它?

Create an array of JLabels and loop over it. 创建一个JLabels数组并在其上循环。

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. 当然,每个索引都应该在循环之前包含一个JLabel This is just an example. 这只是一个例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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