How to check which JTextFields are empty and inform the user about them?

后端 未结 2 725
难免孤独
难免孤独 2021-01-29 13:43

I have a code sample with JTextFields. When a user does not enter the details in some JTextField, and then clicks the \"Register\" button, I want the u

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-29 13:54

    Create an Array of error messages:

    String[] errors = 
    {
        "First Name is missing",
        "Middle Name is missing",
        ...
    };
    

    Then in your looping code you can just reference the Array for the appropriate message. You might want to use a JTextArea since you could have multiple message:

    if (check[i] == 0) 
    {
        textArea.append( errors[i] );
    }
    

    You could even simplify your code by create an Array of text fields then your looping code would be something like:

    for (int i = 0; i < textFields.length; i++) 
    {
        JTextField textField = textFields[i];
        String text = textField.getText();
        int length = text.length();
    
        if (length == 0) 
        {
            textArea.append( ... );
        }
    }
    

    Look to create loops/reusable code. It makes maintenance easier if you ever need to add another text field to test.

提交回复
热议问题