【问题标题】:error: java.lang.ArrayIndexOutOfBoundsException: 0 >= 0错误:java.lang.ArrayIndexOutOfBoundsException:0 >= 0
【发布时间】:2022-01-14 13:54:18
【问题描述】:

求助,我无法删除表格中的最后一行。当我删除其他记录时没有错误,但最后一条,我无法删除它

这是我的代码:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    int row = table1.getSelectedRow();
    if(row >= 0){
    int opt = JOptionPane.showConfirmDialog(null, "Confirm to Delete?", "Delete", JOptionPane.YES_NO_OPTION);
    if(opt==0){
    try{
    Class.forName("com.mysql.cj.jdbc.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307/finals?zeroDateTimeBehavior=CONVERT_TO_NULL", "root", "");
    DefaultTableModel model = (DefaultTableModel) table1.getModel();
    model.removeRow(row);
    String value = (table1.getModel().getValueAt(row, 0).toString());
    String query = "DELETE FROM student WHERE id_num = '"+ value + "'";
    PreparedStatement pst = conn.prepareStatement(query);
    pst.executeUpdate(query);
    JOptionPane.showMessageDialog(this, "Deleted Successfully. \nYour record has been updated.", "Success", JOptionPane.INFORMATION_MESSAGE); 
    }
    catch(Exception ex){ex.printStackTrace();}
    }
    }
    else{JOptionPane.showMessageDialog(this, "Please select a record.", "Error", JOptionPane.INFORMATION_MESSAGE);}
}       

【问题讨论】:

    标签: java mysql sql arrays


    【解决方案1】:

    我怀疑getValueAt(row, 0) 表达式在String value = ... 行中抛出了异常。

    如果是这样的话,我猜你需要切换这两行:

    model.removeRow(row);
    String value = (table1.getModel().getValueAt(row, 0).toString());
    

    如果删除最后一行,则表模型为空。这就是getValueAt(row, 0) 会抛出ArrayIndexOutOfBoundsException 的原因。

    【讨论】:

    • 谢谢@f1sh,它成功了!
    • @ZachMendes 你可以投票和/或接受这个答案,谢谢:)
    猜你喜欢
    • 2014-04-03
    • 2014-05-20
    • 1970-01-01
    • 2014-01-30
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多