Search code examples
javajtextfieldjava-8

Method retake in Java


I'm developing a project in which i have a method to know if a JTextField is empty or not, but i was wondering if a way to implement that method just once and send several JTextFields components to check if they are empty or not exists, if so, could you please tell me how?, here's my sample code.

public static void Vacio(JTextField txt){
    if(txt.getText().trim().equals(null)==true){/*Message*/}
}

Also i would like to know if i could improve the method using some Lambda Expressions, beforehand.


Solution

  • I cannot imagine how adding Lambda expressions can improve what you're trying to do (?).

    Anyway, to check for an empty String I'd probably use:

    field.getText().trim().isEmpty()
    

    You don't need to check for null but you do need to catch NullPointerException in the event that the underlying document in the JTextField is null.

    For the other part of your quesiton, if you really want to check multiple JTextFields in one method you could pass them as a variable length argument list:

    public static void vacio(JTextField... fields) {
        for(JTextField field : fields) {
            try {
                if( field.getText().trim().isEmpty() ) {
                     // do something
                }
            }
            catch(NullPointerException ex) {
                // handle exception (maybe log it?)
            }
        }
    }
    

    and call it like:

    vacio(field1, field2, field3);
    

    But, generally speaking, keeping functions brief and only doing one thing is usually better than trying to make a function do too much.

    One final aside, your method is named Vacio but java naming conventions suggest you should compose method names using mixed case letters, beginning with a lower case letter and starting each subsequent word with an upper case letter.