Reputation: 21
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
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
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