Zach Starnes
Zach Starnes

Reputation: 3198

Throw error if JTextField is empty

I am trying to write a try catch block that will throw an exception if the user does not enter a name and just presses enter or okay I seem to be having issues because it doesn't throw anything it just accepts the blank and continues. Can someone help me? Thanks in advance!

here is the function:

public String setOwnerName() {
        boolean isName = false;

        while(!isName) {
            try {
                this.ownerName = JOptionPane.showInputDialog(null, "Enter the account owner's name.", "Owner's Name", JOptionPane.PLAIN_MESSAGE);
                if(this.ownerName != "") {
                    isName = true;  
                }
            } catch(IllegalArgumentException e) {
                JOptionPane.showMessageDialog(null, "Error you did not enter a name, please try again.", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        return this.ownerName;
    }

Upvotes: 0

Views: 8245

Answers (2)

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

Do like this

 try{           
      if(ownerName.trim().isEmpty()) 
      {
          throw new IllegalArgumentException("Input is wrong");
      }
 } catch(IllegalArgumentException e) {

 }

Upvotes: 0

Masudul
Masudul

Reputation: 21961

Empty name does not trow exception. You need to manually check it. Try,

public String setOwnerName() {
  boolean isName = false;

while(!isName) {               
 ownerName = JOptionPane.showInputDialog(null, "Enter the account owner's name.",
               "Owner's Name", JOptionPane.PLAIN_MESSAGE);

  if(ownerName.trim().isEmpty()){
    JOptionPane.showMessageDialog(null,
        "Error you did not enter a name, please try again.", 
       "Error", JOptionPane.ERROR_MESSAGE);
  }
  else{
      isName = true;
      }               
   }// end of while

    return ownerName;
}

Upvotes: 1

Related Questions