如何将i值插入变量?

时间:2019-09-03 18:24:28

标签: java arrays loops for-loop

我有5个textFields,它们的顺序为book1TextField, book2TextField.book3.,book4.,book5。我希望将变量i插入到这些textFields中,使其像book(i)TextField.getText()一样,这样我就不必一个接一个地做。

for (int i = 0; i < 5; i++){
    bookQuantities[i] = Integer.parseInt(book1TextField.getText());
    System.out.println(bookQuantities[i]);
}

2 个答案:

答案 0 :(得分:0)

创建了这些TextField后,您应该将它们存储在ArrayList<TextField>中,以便以后使用。然后,您可以轻松编写如下内容:

for(int i = 0; i < bookTextFields.size(); i++) {
    bookQuantities[i] = Integer.parseInt(bookTextFields.get(i).getText());
}

答案 1 :(得分:0)

您可以这样使用instanceof:

int comp = panel.getComponentCount();
int[] bookQuantities = new int [comp];
for (int i = 0; i < comp; i++) {
    if (panel.getComponent(i) instanceof JTextField) {
        JTextField txt = (JTextField) panel.getComponent(i);
        bookQuantities[i] = Integer.parseInt(txt.getText());
        System.out.println(bookQuantities[i]);
    }
}