Search code examples
javajtextfield

How to point out which jTextfield is empty


I have this code sample to see which Jtextfield is empty. I have attached a image of my application too. All I need to know is that, when a user was not entering the details in a specific jTextfield, and click "Register" button, I want the user to be informed about his mistake/s like;

"You haven't entered Student Middle Name" or "You have not entered Student Address" or "You haven't entered Student middle name and Address"

I want the user to inform SPECIFICALLY which jTextfield/s is/are EMPTY and set its/Their background/s RED and stop saving the details into database until he fills all the JtextFields. I have tried many codes but any of it didn't work :(

Here's my Code. I have used the array to check the Jtextfield/s are empty or not, but I don't know how to inform the user which Jtextfield/s is/are causing the problem. Please Help Me :(

public void checkEmpty() {
    String fname = jTextField1.getText();
    String mname = jTextField2.getText();
    String lname = jTextField3.getText();

    String lineone = jTextField4.getText();
    String linetwo = jTextField5.getText();
    String linethree = jTextField6.getText();

    int fnam = fname.length();
    int mnam = mname.length();
    int lnam = lname.length();
    int lineon = lineone.length();
    int linetw = linetwo.length();
    int linethre = linethree.length();

    int[] check = {fnam, mnam, lnam, lineon, linetw, linethre};
    for (int i = 0; i < check.length; i++) {
        if (check[i] == 0) {
            //needs to show which jTextfield/s is/are empty and make their backgrounds RED
        } else {
            //save to database----> I know what I have to do here.
        }
    }
}

Thank you very much :)This is my Application


Solution

  • Do something like below:

    public void checkEmpty() {
        JTextField [] textFields = {jTextField1,jTextField2,jTextField3,jTextField4,jTextField5,jTextField6};
        isInputValid = true;
        for (int i = 0; i < textFields.length; i++) {
            JTextField jTextField = textFields[i];
            String textValue = jTextField.getText().trim();
            if (textValue.length() == 0) {
                //turn background into red
                jTextField.setBackground(Color.RED);
                isInputValid = false;
            }
        }
    
        // now check if input are valid
        if(!isInputValid) return;
    
        //save to database----> I know what I have to do here.
    }