如果不能工作,因为它应该JAVA

时间:2018-04-19 12:03:29

标签: java if-statement button logic

我正在努力使if语句有效,但我不知道如何正确表达它。

Button button_2 = new Button("Delete");
button_2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

这里我选择了我打算稍后操作的行和列。

        int column =0;
        int row = table_1.getSelectedRow(); 
        String id= table_1.getModel().getValueAt(row, column).toString();

                if (id==null) { // won't work as it should ? 
                JOptionPane.showMessageDialog(null, "Please select a row to delete!");


                  }else {


                        try{ 
                            String query3 = "DELETE FROM hostel_dtrm  WHERE id=?";
                            PreparedStatement pst= conn1.prepareStatement(query3);

                                pst.setString(1, id);
                                pst.executeUpdate();


                     // Printing the results after Row Deletion
                    String query2= "SELECT * FROM hostel_dtrm";
                    PreparedStatement psts= conn1.prepareStatement(query2);
                    ResultSet rs=psts.executeQuery();

                    table_1.setModel(DbUtils.resultSetToTableModel(rs));

                    // Closing stuff
                      pst.close();
                      rs.close();   

                  JOptionPane.showMessageDialog(null, "Row Deleted");

                   }catch(Exception err){
                        System.err.println(err);    
                        }

            }

        }
    }); 

1 个答案:

答案 0 :(得分:1)

我假设您正在从JTable中选择一行。请注意,如果未选择任何行(documentation here),getSelectedRow()方法将返回-1

因此,在获取该行/列的值之前,您应该检查row是否为-1

...
int column = 0;
int row = table_1.getSelectedRow();
if (row == -1) {
    JOptionPane.showMessageDialog(null, "Please select a row to delete!");
} else {
    String id = table_1.getModel().getValueAt(row, column).toString();
    ...
}