【问题标题】:PLease assist with my JTable Loop Exception请协助我的 JTable 循环异常
【发布时间】:2020-07-30 10:13:47
【问题描述】:

这是我的代码,我试图循环遍历新股票表中的所有行。即使我使用 totalRows - 1 我仍然得到相同的例外。任何帮助将不胜感激。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
int totalRows = newTable.getRowCount();
String tempName = "";
int tempTotal = 0;
System.out.println("total new rows: " + totalRows);

    try {
        for (int i = 0; i < (totalRows - 1); i++) {
            tempName = currentTable.getModel().getValueAt(i, 0).toString();
            tempTotal = Integer.parseInt(currentTable.getModel().getValueAt(i, 1).toString());
            System.out.println("Current Table Product:    " + currentTable.getModel().getValueAt(i, 0).toString());
            System.out.println("Current Table Total:  " + currentTable.getModel().getValueAt(i, 1).toString());

            System.out.println("New Table Product:    " + newTable.getModel().getValueAt(i, 0).toString());
            System.out.println("New Table Temp Total:  " + newTable.getModel().getValueAt(i, 1).toString());

            //if (newTable.getModel().getValueAt(i, 0).toString() == currentTable.getModel().getValueAt(i, 0).toString()) {
            //    int newTempTotal = Integer.parseInt(newTable.getModel().getValueAt(i, 1).toString());
            //    newTotal = newTempTotal + tempTotal;
            //    System.out.println("product:    " + newTable.getModel().getValueAt(i, 0).toString());
            //    System.out.println("grand new total:    " + newTotal);
            //}
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}    

然后我得到以下异常...

java.lang.ArrayIndexOutOfBoundsException: 3 >= 3
at java.util.Vector.elementAt(Vector.java:477)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:648)
at great.meat.AddNewStock.jButton1ActionPerformed(AddNewStock.java:325)
at great.meat.AddNewStock.access$300(AddNewStock.java:23)
at great.meat.AddNewStock$4.actionPerformed(AddNewStock.java:210)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)

【问题讨论】:

  • newTable 的行数是否与currentTable 相同?
  • 是的,现在它的行数相同
  • newTable.getModel() 的行数是否与currentTable.getModel() 相同
  • 是的,newTable 和curentTable 的行数相同
  • 我专门询问了他们的模型行数,而不是 JTable

标签: java swing jtable indexoutofboundsexception


【解决方案1】:

我不知道这两个表有多少行,但你的问题可能出在这一行:

tempName = currentTable.getModel().getValueAt(i, 0).toString();

因为您正在循环使用 newTable 行数:

int totalRows = newTable.getRowCount();

但您正试图从 currentTable 中获取数据。如果 currentTable 的行数比 newTable 少,那么它会抛出异常。

【讨论】:

  • 原来如此,我的新表比当前表的行数多,谢谢
猜你喜欢
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 2023-02-13
  • 1970-01-01
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多