I am working with JOptionPane. it works great when user clicks on the ok button, but when clicking on the cancel button and when closing the message as well, it displays the error message.
private void findActionPerformed(java.awt.event.ActionEvent evt) {
try {
String num = JOptionPane.showInputDialog("Number to Search:");
int number = Integer.parseInt(num);
s.search(number);
}catch (Exception e) {
JOptionPane.showMessageDialog(this, "WRONG INPUT: you must insert integers", "Erorr", JOptionPane.ERROR_MESSAGE);
}
}
Use
private void findActionPerformed(java.awt.event.ActionEvent evt) {
try {
String num = JOptionPane.showInputDialog("Number to Search:");
if(num != null)
{
int number = Integer.parseInt(num);
s.search(number);
}
}catch (Exception e) {
JOptionPane.showMessageDialog(this, "WRONG INPUT: you must insert integers", "Erorr", JOptionPane.ERROR_MESSAGE);
}
}
JOptionPane
returns null
when one closes it or presses cancel. So just check this as the above code shows. And an exception will be thrown when you pass null
to Integer.parseInt()
.