在另一个变量中插入变量

时间:2012-08-02 10:39:36

标签: java swing variables

我有三个文本框ct1,ct2,ct3。我必须使用for循环1到3并检查文本框是否为空。那么,在for循环中,我该如何表示它?例如,

for(i=0;i<=3;i++)
{
    if(ct+i.getText()) // I know I'm wrong
     {
     }

}

3 个答案:

答案 0 :(得分:7)

  

我有三个文本框ct1,ct2,ct3。

首先是你的问题。而不是使用三个单独的变量,创建一个数组或集合:

TextBox[] textBoxes = new TextBox[3];
// Populate the array...

或者:

List<TextBox> textBoxes = new ArrayList<TextBox>();
// Populate the list...

然后在你的循环中:

// Note the < here - not <=
for (int i = 0; i < 3; i++) {
   // If you're using the array
   String text = textBoxes[i].getText();

   // or for the list...
   String text = textBoxes.get(i).getText();
}

或者,如果您不需要索引:

for (TextBox textBox : textBoxes) {
    String text = textBox.getText();
    ...
}

答案 1 :(得分:2)

使用数组

TextBox[] boxes = new TextBox[]{ct1,ct2,ct3};
for(i=0;i<3;i++)
{
    boxes[i].getText(""); // I know I'm wrong
}

答案 2 :(得分:1)

您可以将文本框放在列表中并遍历该列表:

List<TextBox> ctList = new ArrayList<TextBox> ();
list.add(ct1);
list.add(ct2);
list.add(ct3);

for (TextBox ct : ctList) {
    if(ct.getText().equals("expected text")) {
        // do your stuff here
    }
}
相关问题