我有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]);
}
答案 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]);
}
}