Empty String validation for Multiple JTextfield

你说的曾经没有我的故事 提交于 2019-11-29 10:59:16

Just for fun a little finger twitching demonstrating a re-usable validation setup which does use features available in core Swing.

The collaborators:

  • InputVerifier which contains the validation logic. Here it's simply checking for empty text in the field in verify. Note that
    • verify must not have side-effects
    • shouldYieldFocus is overridden to not restrict focus traversal
    • it's the same instance for all text fields
  • a commit action that checks the validity of all children of its parent by explicitly invoking the inputVerifier (if any) and simply does nothing if any is invalid
  • a mechanism for a very simple though generally available error message taking the label of the input field

Some code snippets

// a reusable, shareable input verifier
InputVerifier iv = new InputVerifier() {

    @Override
    public boolean verify(JComponent input) {
        if (!(input instanceof JTextField)) return true;
        return isValidText((JTextField) input);
    }

    protected boolean isValidText(JTextField field) {
        return field.getText() != null && 
                !field.getText().trim().isEmpty();
    }

    /**
     * Implemented to unconditionally return true: focus traversal
     * should never be restricted.
     */
    @Override
    public boolean shouldYieldFocus(JComponent input) {
        return true;
    }

};
// using MigLayout for lazyness ;-)
final JComponent form = new JPanel(new MigLayout("wrap 2", "[align right][]"));
for (int i = 0; i < 5; i++) {
    // instantiate the input fields with inputVerifier
    JTextField field = new JTextField(20);
    field.setInputVerifier(iv);
    // set label per field
    JLabel label = new JLabel("input " + i);
    label.setLabelFor(field);
    form.add(label);
    form.add(field);
}

Action validateForm = new AbstractAction("Commit") {

    @Override
    public void actionPerformed(ActionEvent e) {
        Component source = (Component) e.getSource();
        if (!validateInputs(source.getParent())) {
            // some input invalid, do nothing
            return;
        }
        System.out.println("all valid - do stuff");
    }

    protected boolean validateInputs(Container form) {
        for (int i = 0; i < form.getComponentCount(); i++) {
            JComponent child = (JComponent) form.getComponent(i);
            if (!isValid(child)) {
                String text = getLabelText(child);
                JOptionPane.showMessageDialog(form, "error at" + text);
                child.requestFocusInWindow();
                return false;
            }
        }
        return true;
    }
    /**
     * Returns the text of the label which is associated with
     * child. 
     */
    protected String getLabelText(JComponent child) {
        JLabel labelFor = (JLabel) child.getClientProperty("labeledBy");
        return labelFor != null ? labelFor.getText() : "";
    }

    private boolean isValid(JComponent child) {
        if (child.getInputVerifier() != null) {
            return child.getInputVerifier().verify(child);
        }
        return true;
    }
};
// just for fun: MigLayout handles sequence of buttons 
// automagically as per OS guidelines
form.add(new JButton("Cancel"), "tag cancel, span, split 2");
form.add(new JButton(validateForm), "tag ok");
Android Killer

Take an array of these three JTextField, I am giving an overview

JTextField[] fields = new JTextField[13] 
field[0] = firstname;
field[1] = lastname; //then add remaining textfields

for(int i = 0; i < fields.size(); ++i) {
if(fields[i].getText().isEmpty())
   JOptionPane.showMessageDialog(null, "No data entered");
}

Correct me if i'm wrong, I am not familiar with Swing or awt.HTH :)

vels4j

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.

Here is one way to do it:

public static boolean areAllNotEmpty(String... texts)
{
    for(String s : texts) if(s == null || "".equals(s)) return false;
    return true;
}

// ...

if(areAllNotEmpty(firstName, lastName, emailAddress, phone))
{
    JOptionPane.showMessageDialog(null, "No data entered");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!