0

I implement OOP in my Java assignment. But when I started creating user interface and accept the input I have faced a problem. I wanted to validate the user input of jTextField from user interface using my setter method. I want a pop up to appear when user input is invalid instead of just error message. I know it can be done easily if I implement the validation code directly in the user interface. I don't know which way is better but since I already have all my setter method so I wanted to validate using setter method.

Employee Class

public void setUsername(String username){
    if(username.equals(null)){
        //validation method
    }

User Interface

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    Admin ad = new Admin();
    String username = jTextField6.getText();
    ad.setUsername(username);
}
  
Peter Alsen
  • 320
  • 2
  • 5
  • 15
random
  • 95
  • 1
  • 10
  • 1
    I assume that `jTextField6` is a `JTextField`, in which case method `getText()` will **never** return null but it may return an empty string. Is [input verifier](https://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html#inputVerification) not an option? – Abra Oct 30 '20 at 17:13
  • @Abra but how do the user know what is the valid input if there is no any message. From what i see the input verifier does not allow user to proceed if the input is invalid but does not show a message for correct format of input – random Oct 30 '20 at 18:16
  • Maybe [this answer](https://stackoverflow.com/questions/59677968/how-to-disallow-special-characters-in-jtextfield/59686862#59686862) will help. – Abra Oct 30 '20 at 20:25

1 Answers1

0

Validation must be done in several layers to ensure your application accuracy .But here according to your situation you are trying to validate an user input.So it's a validation which belongs to view layer like you are validating forms in web development.So since you are using Java Swing you need to place your view validation logic inside the controller.Because of that the best way to implement it is like below.

String username = jTextField6.getText();

if(userName.isEmpty()){
    //Place your error message logic here
}else{
     ad.setUsername(username);
}

Hasindu Dahanayake
  • 1,344
  • 2
  • 14
  • 37
  • I intend to use the setter method to validate the input. Not directly validate it in the user interface code. Is there anyway? – random Oct 30 '20 at 17:34
  • Oh i see. Because some of the website mention i can validate an data using setter so i wanted to try it out. I guess it only works on scanner. Thanks. – random Oct 30 '20 at 17:45