开发者

Simple Java Validation

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开发者_Python百科 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


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.


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());


Have a look at the recent JSR-303 standard: http://jcp.org/en/jsr/detail?id=303. It also integrates well with Spring.


In order to test Java application you can use JUNIT http://junit.sourceforge.net/ for whitebox testing

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜