java 使用数组/循环设置 JLabel 的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4664619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting text of JLabel with an array/loop
提问by usw
How can I set the text of a JLabel with a loop? For example:
如何使用循环设置 JLabel 的文本?例如:
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
谢谢
回答by camickr
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] );
}
回答by Mark Peters
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);
}