Events
Validate Swing input data
Text field
How to validate the data entered into a text field
- Like console applications, Swing applications should validate all data entered by the user before processing the data.
- When an entry is invalid, the program needs to display an error message and give the user another chance to enter valid data.
- To test whether a value has been entered into a text field, you can use the getText method of the text field to get a string that contains the text the user entered. Then, you can check whether the length of that string is zero by using its length method.
- To test whether a text field contains valid numeric data, you can code the statement that converts the data in a try block and use a catch block to catch a NumberFormatException.
Code that checks if an entry has been made
if (investmentTextField.getText().length() == 0)
{
JOptionPane.showMessageDialog(this,
"Monthly Investment is "
+ "a required field.\nPlease re-enter.",
"Invalid Entry", JOptionPane.ERROR_MESSAGE);
investmentTextField.requestFocusInWindow();
validData = false;
}
Code that checks if an entry is a valid number
try
{
double d = Double.parseDouble(
investmentTextField.getText());
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(this,
"Monthly Investment "
+ "must be a valid number.\nPlease re-enter.",
"Invalid Entry", JOptionPane.ERROR_MESSAGE);
investmentTextField.requestFocusInWindow();
validData = false;
}