我有一个jTable填充了MySQL数据库中的数据。如果用户选择一行并点击jButton,它会显示一个jDialog,在那里他/她可以编辑与所选行相关的所有数据。它工作得很好,但是当没有选择时,IDE会给出错误消息。我该怎么办?
错误消息:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
我的代码:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int username = 0;
int un_row = jTable1.getSelectedRow();
String uname = jTable1.getModel().getValueAt(un_row, username).toString();
if(morethanzero()) {
PersonalInfoEdit piedit = new PersonalInfoEdit(null, true, uname, perm);
piedit.setLocationRelativeTo(piedit);
piedit.setVisible(true);
}
}
boolean morethanzero(){
if(model.getRowCount() < 0 || model.getColumnCount() < 0) {
JOptionPane.showMessageDialog(null,"There's no selected user!","Error",JOptionPane.ERROR_MESSAGE);
jTable1.requestFocus();
return false;
}
return true;
}
提前谢谢!
答案 0 :(得分:2)
这很简单,只要没有选择行就要考虑到。例如,
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int username = 0;
int un_row = jTable1.getSelectedRow();
if (un_row < 0) {
return; // if no row selected, get out!
}
// .... rest of code here