简体   繁体   English

如何使用for循环递增创建的jlabels的变量名?

[英]How to increment the variable names created jlabels using for loop?

java code: Java代码:

for (int i = 0; i < 10;++i) {
   if (i == 9){
     lbl_ichar.setText(String.valueOf(word.charAt(i)));
   }
}

This code shows error message(compile time error:cannot find symbol symbol: variable class lbl_ichar) under word lbl_ichar .But I have already created jlabels of variable names lbl_0char , lbl_1char , lbl_2char ...... upto lbl_9char . 此代码在单词lbl_ichar下显示错误消息(编译时错误:找不到符号符号:变量类lbl_ichar)。但是我已经创建了变量名称为lbl_0charlbl_1charlbl_2char ......的lbl_2char ......直到lbl_9char

I want to call by the name lbl_ichar instead of using lbl_9char .Is that possible in java? 我想用名称lbl_ichar而不是lbl_icharlbl_9char 。在Java中可以吗? If so how to code it? 如果是这样,如何编码呢?

It looks like you are trying to create a variable name dynamically at runtime: 看来您正在尝试在运行时动态创建变量名:

JLabel lbl_1char = new JLabel();
JLabel lbl_2char = new JLabel();
// ...

for (int i = 0; i < 10; ++i) {
   lbl_ichar.setText(String.valueOf(word.charAt(i)));
   //  ^
}

This does not work. 这是行不通的。 You can not create the variable name at runtime. 您不能在运行时创建变量名称。 Use an array instead: 改用数组:

JLabel[] lbl_char = new JLabel[10];
lbl_char[0] = new JLabel();
lbl_char[1] = new JLabel();
// ...

for (int i = 0; i < lbl_char.length; i++) {
   lbl_char[i].setText(String.valueOf(word.charAt(i)));
}

Or, even better, instead of using raw arrays, use an ArrayList : 或者,甚至更好的是,不使用原始数组,而使用ArrayList

List<JLabel> lbl_char = new ArrayList<>();
lbl_char.add(new JLabel());
lbl_char.add(new JLabel());
// ...

for (JLabel lbl : lbl_char) {
   lbl.setText("Whatever");
}

try to do something likewise, 尝试做同样的事情,

JLabel lb_char[] = new JLable[10]; JLabel lb_char [] =新的JLable [10];

then after into Loop you can refer that labels like this way, 然后进入Loop之后,您可以像这样引用这些标签,

for (int i = 0; i < 10;++i) {

     lbl_char[i].setText(String.valueOf(word.charAt(i)));
} 

You cannot directly use loop variable i value like "lbl_ichar". 您不能直接使用“ lbl_ichar”之类的循环变量i值。

you want to change the value only if your i value is 9, or do you want to set new value for "lbl_9char" ? 您只想在i值为9时更改该值,还是要为“ lbl_9char”设置新值?

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

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