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.
我正在使用JOptionPane。当用户单击“确定”按钮时,它非常有用,但是当单击“取消”按钮时以及关闭消息时,它也会显示错误消息。
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);
}
}
1 个解决方案
#1
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()
.
当一个人关闭它或按下取消时,JOptionPane返回null。所以只需检查一下上面的代码即可。将null传递给Integer.parseInt()时会抛出异常。
#1
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()
.
当一个人关闭它或按下取消时,JOptionPane返回null。所以只需检查一下上面的代码即可。将null传递给Integer.parseInt()时会抛出异常。