I am a web app programmer (mostly PHP/JavaScript/Ajax etc). There is this payroll appplication that I want to code in java. I needed to know where I could find tutorials on how to do basic validation in java e.g. checking if a textfield is null, making sure only integers are allowed etc.
I have this basic program that runs and created a jFrame form:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
double num1, num2, result;
num1 = Double.parseDouble(jTextField1.getText());
num2 = Double.parseDouble(jTextField2.getText());
result = num1 + num2;
jLabel4.setText(String.valueOf(result));
}
How can I for instance get to validate that jTextField's 1 and 2 are not left blank. i.e., to return an error box that lets a user know that both fields cannot be left blank?
I was trying this as a tester:
if(num1 == 0 && num2 == 0)
{
JOptionPane.showMessageDialog(null, "You must fill in all fields");
}
But this doesnt work at all
-
1With the code you have you will get a NumberFormatException if either text is blank. The problem is not just the validation but presenting a useful message to the user. The way I would do it is to have a label next to the field which shows an error in red to indicate what is wrong with the data. (or nothing is fine)Peter Lawrey– Peter Lawrey2011年04月29日 09:54:49 +00:00Commented Apr 29, 2011 at 9:54
4 Answers 4
If it belongs to swing then check
jTextField1.getText().trim().length > 0 && jTextField2.getText().trim().length > 0
or
!jTextField1.getText().equals("") && !jTextField2.getText().equals("")
Also read some tutorial on swing components.
1 Comment
For a beginner like yourself, using a standard library like Apache Commons / Lang will probably be the easiest:
check if a value is numeric:
// removes whitespace, converts to null if only whitespace,
// checks whether the remeining string is numeric only
StringUtils.isNumeric(StringUtils.stripToNull(jTextField1.getText()));
Get the numeric value:
int value = Integer.parseInt(jTextField.getText().trim());
Comments
Have a look at the recent JSR-303 standard: http://jcp.org/en/jsr/detail?id=303. It also integrates well with Spring.
Comments
In order to test Java application you can use JUNIT http://junit.sourceforge.net/ for whitebox testing