Setting text of JLabel with an array/loop

耗尽温柔 提交于 2019-12-11 07:00:23

问题


How can I set the text of a JLabel with a loop? 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?

Thanks


回答1:


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[] labels = new JLabel[cur.length];

for (int i = 0 i < cur.length; i++)
{
    labels[i] = new JLabel( cur[i] );
}



回答2:


You can make an array of JLabels instead:

JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};
for ( JLabel label : labels ) {
   label.setText("something");
   panel.add(label);
}


来源:https://stackoverflow.com/questions/4664619/setting-text-of-jlabel-with-an-array-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!