AsySyah
AsySyah

Reputation: 21

if statament not working

My If Statement not working

Basically i have a button that i design in my form and when i execute everything was suppose to save user data to database and show a dialog box "Data Saved". Everything was fine and now i want to insert a condition so if user did not enter a value it will show a dialog box and user need to reenter again. The problem now it does check for my condition until it show the dialog box but when i press ok it will save an empty value and show dialog box "data saved". Below is my code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    
    if (txt_pangkat.getText().equals("")||icon_image1 == null) {
        JOptionPane.showMessageDialog(null,"Please Insert a value");
        dispose();
    }
    try { 
       
        String sql="insert into KKKB1 (Pangkat,Sains)values (?,?)";
        pst=conn.prepareStatement(sql);
        pst.setString(1, txt_pangkat.getText());
        pst.setBytes(2, icon_image1);
   
        pst.execute();
   
        JOptionPane.showMessageDialog(null, "Data Saved");
        txt_pangkat.setText("");
 
        back();
   
  
       }
       catch(Exception e){
           JOptionPane.showMessageDialog(null, e);
       } finally {

           try {
            
               pst.close();
           }
           catch(Exception e){
           }
      }
}  

Upvotes: 0

Views: 72

Answers (2)

Hungry Blue Dev
Hungry Blue Dev

Reputation: 1325

An uncommon (but elegant) method is to use the (underused) assertion statement:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
    try{
        assert !txt_pangkat.getText().equals("");
        assert icon_image1 != null;
    }catch(Exception e){
        JOptionPane.showMessageDialog(null,"Please Insert a value");
        dispose();
    }
    //rest of code...
}

Upvotes: 0

nano_nano
nano_nano

Reputation: 12523

put the rest of your code into an else statement like this:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         


   if (txt_pangkat.getText().trim().equals("")||icon_image1 == null) {
       JOptionPane.showMessageDialog(null,"Please Insert a value");
       dispose();
   } else {
       try {
           String sql="insert into KKKB1 (Pangkat,Sains)values (?,?)";
           pst=conn.prepareStatement(sql);
           pst.setString(1, txt_pangkat.getText());
           pst.setBytes(2, icon_image1);

           pst.execute();

           JOptionPane.showMessageDialog(null, "Data Saved");
           txt_pangkat.setText("");

           back();
       }
       catch(Exception e) {
           JOptionPane.showMessageDialog(null, e);
       }
       finally {
           try {
               pst.close();

           }
           catch(Exception e){}
       }
   }
}

Upvotes: 1

Related Questions