[英]Setting text of JLabel with an array/loop
How can I set the text of a JLabel with a loop? 如何使用循环设置JLabel的文本? For example: 例如:
String cur[]= {"A","B","C"};
JLabel lblA,lblB,lblC;
for(i=0;i < cur.length;i++){
lbl+cur[i].setText("something");
}
what should go in the "lbl+cur[i]" part so it sets the text of the JLabels? 什么应该在“lbl + cur [i]”部分,所以它设置JLabels的文本?
Thanks 谢谢
You can't dynamically create variable names like that. 您无法动态创建这样的变量名称。
If you want to set the value of a label in a loop then you need to create an array of JLabels the same way you create an array of Strings. 如果要在循环中设置标签的值,则需要创建JLabel数组,方法与创建字符串数组的方式相同。
JLabel[] labels = new JLabel[cur.length];
for (int i = 0 i < cur.length; i++)
{
labels[i] = new JLabel( cur[i] );
}
You can make an array of JLabels instead: 您可以改为创建一个JLabel数组:
JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};
for ( JLabel label : labels ) {
label.setText("something");
panel.add(label);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.