Empty String validation for Multiple JTextfield

后端 未结 4 1399
说谎
说谎 2020-12-19 08:02

Is there a way to validate a number of JTextfields in java without the if else structure. I have a set of 13 fields, i want an error message when no entry is given for any o

4条回答
  •  时光取名叫无心
    2020-12-19 08:33

    There are multiple ways to do this, one is

     JTextField[] txtFieldA = new JTextField[13] ;
     txtFieldFirstName.setName("First Name") ; //add name for all text fields
     txtFieldA[0] = txtFieldFirstName ;
     txtFieldA[1] = txtFieldLastName ;
     ....
    
     // in action event
     for(JTextField txtField : txtFieldA) {
       if(txtField.getText().equals("") ) {
          JOptionPane.showMessageDialog(null, txtField.getName() +" is empty!");
          //break it to avoid multiple popups
          break;
       }
     }
    

    Also please take a look at JGoodies Validation that framework helps you validate user input in Swing applications and assists you in reporting validation errors and warnings.

提交回复
热议问题