if(buttonPressed.equals(button))
{
try {
// try something
}
catch (NumberFormatException ex) {
// do something
}
}
The // try something
should be the code where you're getting the input text and parsing (ex Integer.parseInt(textField.getText())
). If the parse doesn't work because something than a number is not entered, it will throw a NumberFormatException
See Exceptions tutorial if you need more information on how to use exceptions
Edit: Method
Something simple like this would work
public int parseInput(String input) throws NumberFormatException {
return Integer.parseInt(input);
}
Or something like this if you want to catch the exception
public static int parseInput(String input) {
int number = 0;
try {
number = Integer.parseInt(input);
} catch (NumberFormatException ex) {
someLabel.setText("Must be a number");
return -1; // return 0
}
}
Then in your actionPerformed you can do something like this
if(buttonPressed.equals(button))
{
int n;
if (parseInput(textField.getText()) != -1){
n = parseInput(textField.getText());
// do something with n
}
}
Edit: boolean Method
public boolean isNumber(String input){
for (char c : input.toCharArray()){
if (!Character.isDigit(c))
return false;
}
return true;
}
Usage
if(buttonPressed.equals(button))
{
if (isNumber(textField.getText()){
// do something
}
}
Edit: or to catch
exception
public boolean isNumber(String input){
try {
Integer.parseInt(input);
return true;
} catch (NumberFormatException ex){
return false;
}
}