Empty String validation for Multiple JTextfield

后端 未结 4 1392
说谎
说谎 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:31

    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 :)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-19 08:36

    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");
    
    0 讨论(0)
  • 2020-12-19 08:42

    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");
    }
    
    0 讨论(0)
提交回复
热议问题