使用for循环设置从数据库中获取的jTextFields中的值

时间:2013-05-07 05:13:00

标签: java swing oop reflection jtextfield

我想执行查询并将这些值添加到循环内的文本字段中。我希望有这样的东西,

String query = "select student_id,String firstName,lastName,address,phoneNumber,mobileNumber,fathersName,fathersOccupation,mothersName,nationality,qualification from student where student_id='" + jTextField5.getText().toString() + "'";
        ResultSet rs = DBOptions.executeSQLQuery(query);
        rs.next();
        for(int i=0; i < 11; i++){
            String s = rs.getString(i+1);
            String field = "jTextField"+i+".setText(s)";//can you do something like this and use the string to add values to individual textFeilds?
        }

我曾尝试过查看ArrayList和其他方式,但它们似乎令人困惑......

1 个答案:

答案 0 :(得分:0)

将所有jtextField存储在ArrayList中,但要确保顺序中的已插入

List<JTextField> fieldList = new ArrayList<JTextField>();
fieldList.add(jtextField1); //gets stored at index 0
fieldList.add(jtextField2); //gets stored at index 1
...
fieldList.add(jtextField10); //gets stored at index 10

然后在你的方法

for(int i=0; i < 11; i++){
    String s = rs.getString(i+1);
    fieldList.get(i).setText(s);
}