2017-03-23 26 views
0

0我已插入亩JFrame并试图从结果集中添加行,但一个JTable它显示java.lang.ArrayIndexOutOfBoundsException:0> =在摆动

Exception in thread "AWT-EventQueue-0"java.lang.ArrayIndexOutOfBoundsException: 0 >= 0 

代码如下:

String billSelect_Sql = "select bill.bill_id, transaction.date, bill.product_desc, bill.quantity, bill.rate, transaction.debt, transaction.crdt, transaction.closing_balance from bill, transaction where bill.user_id = transaction.user_id and bill.user_id = '"+uid+"';"; 
      Statement ST2=conn.createStatement(); 
      ResultSet RS2 = ST2.executeQuery(billSelect_Sql) 

      int rowCount = 0; 
      while(RS2.next()){ 

       billing_tab.getModel().setValueAt(RS2.getString("bill_id"), rowCount, 1); 
       billing_tab.getModel().setValueAt(RS2.getString("date"), rowCount, 2); 
       billing_tab.getModel().setValueAt(RS2.getString("product_desc"), rowCount, 3); 
       billing_tab.getModel().setValueAt(RS2.getInt("quantity"), rowCount, 4); 
       billing_tab.getModel().setValueAt(RS2.getDouble("rate"), rowCount, 5); 
       billing_tab.getModel().setValueAt(RS2.getDouble("debt"), rowCount, 6); 
       billing_tab.getModel().setValueAt(RS2.getDouble("crdt"), rowCount, 7); 
       billing_tab.getModel().setValueAt(RS2.getDouble("closing_balance"), rowCount, 8); 
       rowCount = rowCount+1; 
      } 

     }catch(ClassNotFoundException | SQLException | NumberFormatException e){ 
      JOptionPane.showMessageDialog(null, e); 
      System.out.println(e); 
     } 

billing_tab是我在jframe上的jTable的变量名。 在点显示错误:

billing_tab.getModel().setValueAt(RS2.getString("bill_id"), rowCount, 1); 

我错过了什么与此代码添加?

+0

添加你的代码。 –

+0

你能说明你是如何实例化数组的吗? – yashpandey

+0

我认为你的表没有足够的行。迭代时只需增加表格中的行数。 –

回答

1

首先变量名称(即RS2,ST2)不应以大写字符开头。那么名称也应该更具描述性。大部分变量名都是正确的,但不是全部。始终如一!!!

试图从结果中添加行设置

billing_tab.getModel().setValueAt(RS2.getString("bill_id"), rowCount, 1); 
    billing_tab.getModel().setValueAt(RS2.getString("date"), rowCount, 2); 
    billing_tab.getModel().setValueAt(RS2.getString("product_desc"), rowCount, 3); 
    billing_tab.getModel().setValueAt(RS2.getInt("quantity"), rowCount, 4); 
    billing_tab.getModel().setValueAt(RS2.getDouble("rate"), rowCount, 5); 
    billing_tab.getModel().setValueAt(RS2.getDouble("debt"), rowCount, 6); 
    billing_tab.getModel().setValueAt(RS2.getDouble("crdt"), rowCount, 7); 
    billing_tab.getModel().setValueAt(RS2.getDouble("closing_balance"), rowCount, 8); 
    rowCount = rowCount+1; 

你的模型是空的,所以没有数据改变。不要尝试使用setValueAt(...)方法将数据添加到模型中。该方法仅用于“更改”模型中的现有数据。

相反,您想添加一行新的数据。所以你的代码应该是这样的:

Vector<Object> row = new Vector<Object>(); 
row.addElement(RS2.getString("bill_id")); 
row.addElement(RS2.getSTring("date")); 
... 
billing_tab.getModel().addRow(row);