java swing problem (showInputDialog of JOptionPane)?

naijagunner

New member
Hello. I have a little problem using the showInputDialog. I know that if you hit the cancel button it returns null as the answer and if you type in the input box it returns what you typed as a string.

I know how to deal with the problem if it returns null. But the problem now is that I want to force the user to input an integer in the dialog box because I need the user's input(the integer for something else). If i type a text and click ok i have a NumberFormatException beacuse of String.valueOf()....

So it all boils down to how to detect if the input is an integer.

I tried to surround it with a try{ ... }catch, tried with do...while loop and parseInt methods all to no avail.
I know i can use a comboBox containing numbers in the dialog box but i dont want to use that method. Here's my code

String str = (String)JOptionPane.showInputDialog(null,
"Enter the volume of the package(It has to be a integer)",
"Package Volume",
JOptionPane.INFORMATION_MESSAGE);
boolean flag = false;
int i;
do{
try{
i = Integer.parseInt(str);
flag = true;
}catch(NumberFormatException e){
JOptionPane.showInputDialog(null,"Eh, I want a digit!");
}
}while(flag==false);
}
}


Thanks
 
Back
Top