2015-10-11 30 views
0

所以我有一個函數,從我的數據庫填充JTable。ArrayIndexOutOfBoundsException錯誤,但我認爲代碼是好的

我這裏有

public static TableModel resultSetToTableModel(ResultSet rs) { 
try { 
    ResultSetMetaData metaData = rs.getMetaData(); 
    int numberOfColumns = metaData.getColumnCount(); 
    Vector<String> columnNames = new Vector<String>(); 

    // Get the column names 
    for (int column = 0; column < numberOfColumns; column++) { 
    columnNames.addElement(metaData.getColumnLabel(column + 1)); 
    } 

    // Get all rows. 
    Vector<Vector<Object>> rows = new Vector<Vector<Object>>(); 

    while (rs.next()) { 
    Vector<Object> newRow = new Vector<Object>(); 

    for (int i = 1; i <= numberOfColumns; i++) { 

       if(isObjectInteger(rs.getObject(i)) && i>1) //checks if the value is Integer else not and is past the first column 
       { 
        System.out.println(i+"="+rs.getObject(i)); 
        String label = columnNames.get(i); //THE ERROR IS ON THIS PART 
        newRow.addElement(getValue((Integer) rs.getObject(i),label)); //gets the value of specific foreign key id from another table 
       } 
       else 
       { 
        System.out.println(i+"="+rs.getObject(i)); 
        newRow.addElement(rs.getObject(i)); 
       } //inside row (new Rows) 
    } 

    rows.addElement(newRow); //outside row 
    } 
    return new DefaultTableModel(rows, columnNames) 
     { 
      @Override 
      public boolean isCellEditable(int row, int column) { 
       return false; 
      } 
     }; 
} catch (Exception e) { 
    e.printStackTrace(); 

    return null; 
} 
} 

我共有8列在我的數據庫System.out.println的輸出是:

的一個人是讓別人裏面的:

1=1 
2=test 
3=A. 
4=test 
5=test 
6=test 

的一個人那裏得到的如果

7=1 
8=23 

正如你可以看到輸出是正確的,但它始終引發數組索引超出範圍:在String label = columnNames.get(i);

回答

1

8錯誤雖然ResultSet.getObject()需要基於一個參數,columnNames是一個矢量,其中基於零其索引。

它因此有效值是0..71..8。換句話說,您的if聲明的第一部分應該是:

System.out.println(i + "=" + rs.getObject(i)); 
String label = columnNames.get(i-1); // NOT "i". 
+0

謝謝。我對此讚不絕口。我從未見過那個。我專注於其他變數。現在我可以去睡覺了。我可以在5分鐘內接受這個答案 – Roch

+1

@Roch:先睡覺,隨時可以接受這個答案:-) – paxdiablo

相關問題