java: validating that all text fields in GUI are completed

China☆狼群 提交于 2019-12-04 10:29:35

The getText() method will not return null. It will return the empty String ("").

Your test should be something like:

if ( textField.getText().trim().length() == 0 )
  // error

Old question, but it's generally a good idea to create a "validation" helper method that does all the validation first, then if it checks out you can load all the values into whatever you're doing (variables, class attributes to instantiate something, etc).

eg:

private class createAccountListener implements ActionListener
{
  public void actionPerformed(ActionEvent ae)
  {
    // first we validate all fields... if they pass, we do
    // the rest of the code, otherwise we let the failed validation
    // code tell user what happened, and skip the rest of the code
    if ( validateFields() )
    {
      String fname = fieldFirstName.getText();
      String lname = fieldFirstName.getText();
      int    age   = fieldAge.getText();
    }
  }
}

// test all text fields for input 
public boolean validateFields()
{
  if (! validateField( fieldFirstName, "Please enter a first name")
    return false;
  else
  if (! validateField( fieldLastName, "Please enter a last name")
    return false;
  else
  if (! validateInteger( fieldAge, "Please enter an age greater then 0")
    return false;
  else
    return true;
}

// test if field is empty
public boolean validateField( JTextField f, String errormsg )
{
  if ( f.getText().equals("") )
    return failedMessage( f, errormsg );
  else
    return true; // validation successful
}

public boolean validateInteger( JTextField f, String errormsg )
{
  try
  {  // try to convert input to integer
    int i = Integer.parseInt(f.getText());

    // input must be greater then 0
    // if it is, success
    if ( i > 0 )
      return true; // success, validation succeeded
   }
   catch(Exception e)
   {
      // if conversion failed, or input was <= 0,
      // fall-through and do final return below
   }
   return failedMessage( f, errormsg );
}

public boolean failedMessage(JTextField f, String errormsg)
{
  JOptionPane.showMessageDialog(null, errormsg); // give user feedback
  f.requestFocus(); // set focus on field, so user can change
  return false; // return false, as validation has failed
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!