Reputation: 61
I have a few buttons on my panel and everytime I click on it an input dialog box appears. It has an inbuilt cancel button. Now, when i click on the cancel button in the beginning of the code without entering the quantity in the dialog box, it says, "This is an invalid" number. This line has to only appear if the user enters alphabets or symbols, and not on pressing cancel. Can we solve this?
Upvotes: 1
Views: 159
Reputation: 120
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if (Input.matches(("((-|\+)?[0-9]+(\.[0-9]+)?)+"))) { JOptionPane.showMessageDialog(null,"valid number"); } else{ JOptionPane.showMessageDialog(null,"This is an invalid number"); }
Upvotes: 0
Reputation: 120
Try doing,
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if (Input.equals(""))
{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}
The following link explains it even better: Simple Data Validation.
Upvotes: 0
Reputation: 205785
First you need a way to decide if a String
represents a number; the method below uses Double.valueOf()
to decide.
private Double valueOf(String s) {
try {
return Double.valueOf(s);
} catch (NumberFormatException e) {
return null;
}
}
Here's an example of how you might use the method:
private void display() {
String input = JOptionPane.showInputDialog(
null, "Enter a number?", "Number", JOptionPane.QUESTION_MESSAGE);
Double value = valueOf(input);
JOptionPane.showMessageDialog(null, "The value " + input
+ " is " + (value != null ? "valid" : "invalid") + ".");
}
See also How to Make Dialogs.
Upvotes: 2