Search code examples
javaswingjtextfieldis-empty

How to Check if all the JTexFields are empty or not?


I am using a for loop to create 9 JTextFields and this is working fine. My problem is, I want to check of all the these JTextField is empty or not' at one time. I know there is a method like:

if (textbox.getText().trim().equals(""))

to check if the JTextField is empty or not, But I am not sure if it is suitable for the method that I am using for JTextField. Below is my for loop:

       for (int index = 1; index <=9; index++)
            {
                JTextField field = new JTextField(3);
                field.setPreferredSize(new Dimension(150, 50));
                field.setHorizontalAlignment(JTextField.CENTER);
                field.setEditable(false);
                second.add(field);
                second.add(Box.createHorizontalStrut(10));
                second.add(Box.createVerticalStrut(10));

            }   

Solution

  • Store your text fields in a List so that you can iterate over them later.

    public class ClassContainingTextFields {
        private final ArrayList<JTextField> textFields = new ArrayList<>();
    
        // ... inside the method that creates the fields ...
            for (int i = 0; i < 9; i++) {
                JTextField field = new JTextField(3);
                //  .. do other setup 
                textFields.add(field);
            }
    
    
        /**
         * This method returns true if and only if all the text fields are empty
         **/
        public boolean allFieldsEmpty() {
            for (JTextField textbox : textFields) {
                if (! textbox.getText().trim().isEmpty() ) {
                    return false;   // one field is non-empty, so we can stop immediately
                }
            }
            return true;  // every field was empty (or else we'd have stopped earlier)
        }
        // ....
    }