java.lang.ArrayIndexOutOfBoundsException:0> = 0 in swing

时间:2017-03-23 09:51:47

标签: java swing exception jtable

我在mu JTable中插入了JFrame并试图从结果集中添加行,但它正在显示

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);

我是否错过了使用此代码添加的任何内容?

1 个答案:

答案 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 );
相关问题